﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;

using ExcelCOM = Microsoft.Office.Interop.Excel;

namespace HITs
{
    /// <summary>
    /// NGD:1-Open:2-High:3-Low:4-Close:5-Volume:6
    /// </summary>
    partial class DanhSachCoPhieu
    {
        #region ------ Field -----------
        private List<CoPhieu> _danhSachCoPhieu;
        private string _ngayBatDau;
        private string _ngayKetThuc;

        #endregion

        #region ------ Constructors ----
        public DanhSachCoPhieu()
        {
            _danhSachCoPhieu = new List<CoPhieu>();
    
        }

        public DanhSachCoPhieu(DanhSachCoPhieu dsCoPhieuFull, int id, int length)
        {
            this._danhSachCoPhieu = new List<CoPhieu>();
            List<NgayGiaoDich> listNgayGiaoDich;
            foreach (CoPhieu cp in dsCoPhieuFull._danhSachCoPhieu)
            {
                if (cp.DanhSachNgayGiaoDich.Count >= id + length && length >= 15)
                {
                    listNgayGiaoDich = new List<NgayGiaoDich>();
                    for (int i = id; i < length; i++)                    
                        listNgayGiaoDich.Add(cp.DanhSachNgayGiaoDich[i]);
                    if (listNgayGiaoDich.Count > 0)
                        this._danhSachCoPhieu.Add(new CoPhieu(cp.TenCoPhieu, listNgayGiaoDich));
                }
            }
        }
        #endregion

        #region ------ Methods ---------

        #region *** Load-Write File - File_
        /// <summary>
        /// Load danh sách cổ phiếu 
        /// </summary>
        /// <param name="listData">List đã được load sẵn - có sẵn khi load list tất cả ngày giao dịch trong file
        /// hàm CoreFunctions.LayListNgayGiaoDich_OutFile</param>
        /// <param name="ngayBatDau"></param>
        /// <param name="ngayKetThuc"></param>
        public void File_LoadDanhSachCoPhieu(List<List<string>> listData, string ngayBatDau, string ngayKetThuc)
        {
            int idDanhSachCoPhieu;
            this._danhSachCoPhieu = new List<CoPhieu>();

            foreach (List<string> CoPhieu_NgayGiaoDich in listData)
                if (CoreFunctions.KiemTra_NgayNamGiuaBatDauVaKetThuc(CoPhieu_NgayGiaoDich[1], ngayBatDau, ngayKetThuc) == true)
                {
                    idDanhSachCoPhieu = KiemTra_DanhSachCoPhieuChuaCoPhieu(CoPhieu_NgayGiaoDich[0]);
                    if (idDanhSachCoPhieu != -1)
                        _danhSachCoPhieu[idDanhSachCoPhieu].Xuly_ThemNgayGiaoDich(new NgayGiaoDich(CoPhieu_NgayGiaoDich[1], CoPhieu_NgayGiaoDich[2]
                            , CoPhieu_NgayGiaoDich[5], CoPhieu_NgayGiaoDich[3], CoPhieu_NgayGiaoDich[4], CoPhieu_NgayGiaoDich[6]));
                    else
                    {
                        _danhSachCoPhieu.Add(new CoPhieu(CoPhieu_NgayGiaoDich[0]));
                        _danhSachCoPhieu[_danhSachCoPhieu.Count - 1].Xuly_ThemNgayGiaoDich(new NgayGiaoDich(CoPhieu_NgayGiaoDich[1], CoPhieu_NgayGiaoDich[2]
                            , CoPhieu_NgayGiaoDich[5], CoPhieu_NgayGiaoDich[3], CoPhieu_NgayGiaoDich[4], CoPhieu_NgayGiaoDich[6]));
                    }
                }

            ///Sắp xếp danh sách giao dịch/cổ phiểu theo ngày giao dịch DES và danh sách cổ phiếu theo tên ASC
            for (int i = 0; i < _danhSachCoPhieu.Count; i++)
                _danhSachCoPhieu[i].Xuly_SapXepTheoNgayGiaoDich();
            this.Sapxep_DanhSachCoPhieuTheoTen();

            _ngayBatDau = ngayBatDau;
            _ngayKetThuc = ngayKetThuc;

            LoaiBoCoPhieuCoSoNgayGiaoDichDuoi15Ngay();

            File_CapNhatMaNganh();
        }

        public void File_LoadDanhSachCoPhieu(List<List<string>> listData)
        {
            int idDanhSachCoPhieu;
            this._danhSachCoPhieu = new List<CoPhieu>();
            foreach (List<string> CoPhieu_NgayGiaoDich in listData)
            {
                idDanhSachCoPhieu = KiemTra_DanhSachCoPhieuChuaCoPhieu(CoPhieu_NgayGiaoDich[0]);
                if (idDanhSachCoPhieu != -1)
                    _danhSachCoPhieu[idDanhSachCoPhieu].Xuly_ThemNgayGiaoDich(new NgayGiaoDich(CoPhieu_NgayGiaoDich[1], CoPhieu_NgayGiaoDich[2]
                        , CoPhieu_NgayGiaoDich[5], CoPhieu_NgayGiaoDich[3], CoPhieu_NgayGiaoDich[4], CoPhieu_NgayGiaoDich[6]));
                else
                {
                    _danhSachCoPhieu.Add(new CoPhieu(CoPhieu_NgayGiaoDich[0]));
                    _danhSachCoPhieu[_danhSachCoPhieu.Count - 1].Xuly_ThemNgayGiaoDich(new NgayGiaoDich(CoPhieu_NgayGiaoDich[1], CoPhieu_NgayGiaoDich[2]
                        , CoPhieu_NgayGiaoDich[5], CoPhieu_NgayGiaoDich[3], CoPhieu_NgayGiaoDich[4], CoPhieu_NgayGiaoDich[6]));
                }
            }

            ///Sắp xếp danh sách giao dịch/cổ phiểu theo ngày giao dịch DES và danh sách cổ phiếu theo tên ASC
            for (int i = 0; i < _danhSachCoPhieu.Count; i++)
                _danhSachCoPhieu[i].Xuly_SapXepTheoNgayGiaoDich();
            this.Sapxep_DanhSachCoPhieuTheoTen();

            LoaiBoCoPhieuCoSoNgayGiaoDichDuoi15Ngay();
            File_CapNhatMaNganh();
        }

        public void File_AddCoPhieu(List<List<string>> listData)
        {
            int idDanhSachCoPhieu;
       
            foreach (List<string> CoPhieu_NgayGiaoDich in listData)
            {
                idDanhSachCoPhieu = KiemTra_DanhSachCoPhieuChuaCoPhieu(CoPhieu_NgayGiaoDich[0]);
                if (idDanhSachCoPhieu != -1)
                    _danhSachCoPhieu[idDanhSachCoPhieu].Xuly_ThemNgayGiaoDich(new NgayGiaoDich(CoPhieu_NgayGiaoDich[1], CoPhieu_NgayGiaoDich[2]
                        , CoPhieu_NgayGiaoDich[5], CoPhieu_NgayGiaoDich[3], CoPhieu_NgayGiaoDich[4], CoPhieu_NgayGiaoDich[6]));
                else
                {
                    _danhSachCoPhieu.Add(new CoPhieu(CoPhieu_NgayGiaoDich[0]));
                    _danhSachCoPhieu[_danhSachCoPhieu.Count - 1].Xuly_ThemNgayGiaoDich(new NgayGiaoDich(CoPhieu_NgayGiaoDich[1], CoPhieu_NgayGiaoDich[2]
                        , CoPhieu_NgayGiaoDich[5], CoPhieu_NgayGiaoDich[3], CoPhieu_NgayGiaoDich[4], CoPhieu_NgayGiaoDich[6]));
                }
            }
        }

        /// <summary>
        /// Load từ danh sách cổ phiếu khác nhưng 
        /// </summary>
        /// <param name="listCP"></param>
        /// <param name="ngayBatDau"></param>
        /// <param name="ngayKetThuc"></param>
        public void File_LoadDanhSachCoPhieu(DanhSachCoPhieu listCP, string ngayBatDau, string ngayKetThuc)
        {
            this._danhSachCoPhieu = new List<CoPhieu>();
            List<NgayGiaoDich> listNgayGiaoDich;
            foreach (CoPhieu CP in listCP._danhSachCoPhieu)
            {
                listNgayGiaoDich = CP.Xuly_RutDanhSachNgayGiaoDich(ngayBatDau, ngayKetThuc);
                this._danhSachCoPhieu.Add(new CoPhieu(CP.TenCoPhieu, listNgayGiaoDich));
            }
            ///Sắp xếp danh sách giao dịch/cổ phiểu theo ngày giao dịch DES và danh sách cổ phiếu theo tên ASC
            for (int i = 0; i < _danhSachCoPhieu.Count; i++)
                _danhSachCoPhieu[i].Xuly_SapXepTheoNgayGiaoDich();
            this.Sapxep_DanhSachCoPhieuTheoTen();

            _ngayBatDau = ngayBatDau;
            _ngayKetThuc = ngayKetThuc;

            LoaiBoCoPhieuCoSoNgayGiaoDichDuoi15Ngay();
        }

        public void File_WriteFileGiaThiTruong()
        {
            List<string> listStr = new List<string>();
            listStr.Add(CoreFunctions.HeaderFile);
            string text = "";
            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                if (CP.DanhSachGiaDongCua.Count == 0)
                    continue;
                text = CP.TenCoPhieu + "\t" + CP.DanhSachGiaDongCua[0];
                listStr.Add(text);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_GiaDongCuaMoiNhat.txt", listStr);
        }

        public void File_WriteFileTrungbinhGia10Ngay()
        {          
            List<string> listStr = new List<string>();
            listStr.Add(CoreFunctions.HeaderFile);
            string text = "";
            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                text = CP.TenCoPhieu + "\t" + CP.GiaDongCuaTB10Ngay;
                listStr.Add(text);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_GiaDongCuaTB10Ngay.txt", listStr);
        }

        public void File_CapNhatMaNganh()
        {
            List<string> fileload = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath + @"\Data\Nganh_DanhSachPhanNganh.txt");
            List<List<string>> listPhanNganh = new List<List<string>>();
            foreach (string list in fileload)
            {
                List<string> listCP = new List<string>();
                string[] part = list.Split(new string[] { "\t", " " }, StringSplitOptions.RemoveEmptyEntries);
                if (part.Length > 0)
                {
                    listCP.AddRange(part);
                    listPhanNganh.Add(listCP);
                }
            }
            fileload = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath + @"\Data\Nganh_MaNganh_TenNganh.txt");
            List<string> listMaNganh = new List<string>();
            foreach (string list in fileload)
            {
                string[] part = list.Split(new string[] { "\t"}, StringSplitOptions.RemoveEmptyEntries);
                listMaNganh.Add(part[0]);
            }

            if (listMaNganh.Count == listPhanNganh.Count)
            {
                for (int i = 0; i < listMaNganh.Count; i++)
                {
                    foreach (string tenCP in listPhanNganh[i])
                        for (int j = 0; j < this._danhSachCoPhieu.Count; j++)
                            if (_danhSachCoPhieu[j].TenCoPhieu == tenCP)
                                _danhSachCoPhieu[j].MaNganh = listMaNganh[i];
                }
            }
        }
        #endregion

        #region *** Xử lý - Xuly_
        public void Xuly_ThemCoPhieu(CoPhieu CPmoi)
        {
            bool flag = false;
            foreach (CoPhieu cp in _danhSachCoPhieu)
                if (cp.TenCoPhieu == CPmoi.TenCoPhieu)
                {
                    flag = true;
                    break;
                }
            if (!flag)
            {
                _danhSachCoPhieu.Add(CPmoi);
            }
        }

        public void Xuly_CreateListPortfolio()
        {
            List<string> listNamePortfolio = new List<string>();
            List<List<string>> listNameOfCP = new List<List<string>>();
            List<List<float>> listPercent = new List<List<float>>();
            List<string> listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath + @"\HOSE\ListPortfolio.txt");
            int index = -1;
            for (int i = 1; i < listFile.Count; i++)
            {
                string[] part = listFile[i].Split(new string[] { "\t", "_", " " }, StringSplitOptions.RemoveEmptyEntries);
                listNamePortfolio.Add(part[0]);
                listNameOfCP.Add(new List<string>());
                listPercent.Add(new List<float>());
                index++;
                for (int j = 1; j < part.Length; j += 2)
                {
                    listNameOfCP[index].Add(part[j]);
                    listPercent[index].Add(float.Parse(part[j + 1]));
                }
            }

            for (int i = 0; i < listNamePortfolio.Count; i++)
            {
                CoPhieu cp = new CoPhieu(listNamePortfolio[i]);
                List<List<NgayGiaoDich>> listNgayGiaoDich = new List<List<NgayGiaoDich>>();

                #region Xác định danh mục có số ngày giao dịch ít nhất
                int min = 9999999;
                for (int j = 0; j < listNameOfCP[i].Count; j++)
                    if (min > this.KiemTra_SoNgayGiaoDich(listNameOfCP[i][j]))
                        min = this.KiemTra_SoNgayGiaoDich(listNameOfCP[i][j]);
                #endregion

                #region Tạo list ngày giao dịch
                for (int j = 0; j < listNameOfCP[i].Count; j++)
                    foreach (CoPhieu cophieu in _danhSachCoPhieu)
                        if (cophieu.TenCoPhieu == listNameOfCP[i][j])
                        {
                            listNgayGiaoDich.Add(cophieu.DanhSachNgayGiaoDich);
                            break;
                        }
                #endregion
                if (min > 10)
                {
                    cp.Xuly_TaoTheoDanhMuc(listPercent[i], listNgayGiaoDich, min);
                    _danhSachCoPhieu.Add(cp);
                }
            }
        }

        /// <summary>
        /// Tính ma trận đồng dạng của các cổ phiếu dựa trên Cosine. 
        /// Tính theo 3 tham số cơ bản: giá, khối lượng giao dịch và giá trị giao dịch
        /// </summary>
        /// <param name="Case">
        /// 1: tính theo giá
        /// 2: tính theo khối lượng giao dịch
        /// 3: tính theo giá trị giao dịch
        /// Mặc định tính theo giá
        /// </param>
        /// <param name="listCoPhieuKhongXuLy">danh sách cổ phiếu không được xử lý (không đủ ngày giao dịch với các cổ phiếu</param>
        /// <returns>Ma trận đối xứng qua đường chéo chính</returns>
        public float[,] Xuly_TinhMaTranDongDang_Cosine(int Case, out int levelMatrix)
        {
            /// Nếu các cổ phiếu có số ngày không bằng với số ngày giao dịch quy định thì nó sẽ không đồng dạng           
            levelMatrix = _danhSachCoPhieu.Count;
            float[,] result = new float[levelMatrix, levelMatrix];
            float dongdang = 0f;

            for (int i = 0; i < levelMatrix - 1; i++)
            {
                result[i, i] = 1.0f;
                for (int j = i + 1; j < levelMatrix; j++)
                {
                    #region *Case - Lựa chọn tham số để tính: giá, khối lượng giao dịch và giá trị giao dịch
                    switch (Case)
                    {
                        case 1:
                            {
                                dongdang = CoreFunctions.MR_TinhCosineSimilar(
                                    CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].Xuly_LayDanhSachGiaTongHop())
                                    , CoreFunctions.Tk_GetZScores((_danhSachCoPhieu[j].Xuly_LayDanhSachGiaTongHop())));
                                break;
                            }
                        case 2:
                            {
                                dongdang = CoreFunctions.MR_TinhCosineSimilar(CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].DanhSachKhoiLuongGiaoDich)
                                    , CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[j].DanhSachKhoiLuongGiaoDich));
                                break;
                            }
                        case 3:
                            {
                                dongdang = CoreFunctions.MR_TinhCosineSimilar(CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].Xuly_LayDanhSachGiaTriGiaoDich())
                                    , CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[j].Xuly_LayDanhSachGiaTriGiaoDich()));
                                break;
                            }
                        default:
                            {
                                dongdang = CoreFunctions.MR_TinhCosineSimilar(CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].Xuly_LayDanhSachGiaTongHop())
                                    , CoreFunctions.Tk_GetZScores((_danhSachCoPhieu[j].Xuly_LayDanhSachGiaTongHop())));
                                break;
                            }
                    }
                    #endregion

                    if (dongdang < -1f)
                        dongdang = 0.0f;

                    result[i, j] = dongdang;
                    result[j, i] = dongdang;
                }
            }
            return result;
        }

        public float[,] Xuly_TinhMaTranDongDang_TangGiamCungNhau(int Case, out int levelMatrix)
        {
            /// Nếu các cổ phiếu có số ngày không bằng với số ngày giao dịch quy định thì nó sẽ không đồng dạng           
            levelMatrix = _danhSachCoPhieu.Count;
            float[,] result = new float[levelMatrix, levelMatrix];
            float dongdang = 0f;

            for (int i = 0; i < levelMatrix - 1; i++)
            {
                result[i, i] = 1.0f;
                for (int j = i + 1; j < levelMatrix; j++)
                {
                    #region *Case - Lựa chọn tham số để tính: giá, khối lượng giao dịch và giá trị giao dịch
                    switch (Case)
                    {
                        case 1:
                            {
                                dongdang = CoreFunctions.MR_TinhSimilar_TangGiamCungNhau(
                                    _danhSachCoPhieu[i].DanhSachGiaDongCua_DieuChinh
                                    , _danhSachCoPhieu[j].DanhSachGiaDongCua_DieuChinh);
                                break;
                            }
                        case 2:
                            {
                                dongdang = CoreFunctions.MR_TinhSimilar_TangGiamCungNhau(
                                    _danhSachCoPhieu[i].DanhSachKhoiLuongGiaoDich
                                    , _danhSachCoPhieu[j].DanhSachKhoiLuongGiaoDich);
                                break;
                            }
                        case 3:
                            {
                                dongdang = CoreFunctions.MR_TinhSimilar_TangGiamCungNhau(
                                    _danhSachCoPhieu[i].Xuly_LayDanhSachGiaTriGiaoDich()
                                    , _danhSachCoPhieu[j].Xuly_LayDanhSachGiaTriGiaoDich());
                                break;
                            }
                        default:
                            {
                                dongdang = CoreFunctions.MR_TinhSimilar_TangGiamCungNhau(
                                    _danhSachCoPhieu[i].Xuly_LayDanhSachGiaTongHop()
                                    , _danhSachCoPhieu[j].Xuly_LayDanhSachGiaTongHop());
                                break;
                            }
                    }
                    #endregion

                    //if (dongdang < 0.85f)
                    //    dongdang = 0.0f;
                    //else
                    //    dongdang = 1f;
                    result[i, j] = dongdang;
                    result[j, i] = dongdang;
                }
            }
            return result;
        }

        public float[,] Xuly_TinhMaTranDongDang_Euclid_AvgStd(out int levelMatrix)
        {
            /// Nếu các cổ phiếu có số ngày không bằng với số ngày giao dịch quy định thì nó sẽ không đồng dạng           
            levelMatrix = _danhSachCoPhieu.Count;
            float[,] result = new float[levelMatrix, levelMatrix];
            float dongdang = 0f;

            for (int i = 0; i < levelMatrix - 1; i++)
            {
                result[i, i] = 1.0f;
                for (int j = i + 1; j < levelMatrix; j++)
                {
                    dongdang = CoreFunctions.MR_EuclidDistance_Avg_Std(
                        _danhSachCoPhieu[i].DanhSachGiaDongCua
                        , _danhSachCoPhieu[j].DanhSachGiaDongCua);

                    result[i, j] = dongdang;
                    result[j, i] = dongdang;
                }
            }
            return result;
        }
        /// <summary>
        /// Tính ma trận đồng dạng của các cổ phiếu dựa trên Cosine. 
        /// 
        /// </summary>
        /// <param name="Case">
        /// 1: tính theo giá
        /// 2: tính theo khối lượng giao dịch
        /// 3: tính theo giá trị giao dịch
        /// Mặc định tính theo giá</param>
        /// <param name="chuKy"></param>
        /// <param name="minSimilar"></param>
        /// <param name="levelMatrix"></param>
        /// <returns></returns>
        public float[,] Xuly_TinhMaTranDongDangChuKy_Cosine(int Case, int chuKy, float minSimilar, out int levelMatrix)
        {
            /// Nếu các cổ phiếu có số ngày không bằng với số ngày giao dịch quy định thì nó sẽ không đồng dạng           
            levelMatrix = _danhSachCoPhieu.Count;
            float[,] result = new float[levelMatrix, levelMatrix];
            float dongdang = 0f;

            for (int i = 0; i < levelMatrix - 1; i++)
            {
                result[i, i] = 1.0f;
                for (int j = i + 1; j < levelMatrix; j++)
                {
                    #region *Case - Lựa chọn tham số để tính: giá, khối lượng giao dịch và giá trị giao dịch
                    switch (Case)
                    {
                        case 1:
                            {
                                dongdang = CoreFunctions.MR_TinhSoLuongCosineSimilar(CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].Xuly_LayDanhSachGiaTongHop())
                                    , CoreFunctions.Tk_GetZScores((_danhSachCoPhieu[j].Xuly_LayDanhSachGiaTongHop())), chuKy, minSimilar);
                                break;
                            }
                        case 2:
                            {
                                dongdang = CoreFunctions.MR_TinhSoLuongCosineSimilar(CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].DanhSachKhoiLuongGiaoDich)
                                    , CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[j].DanhSachKhoiLuongGiaoDich), chuKy, minSimilar);
                                break;
                            }
                        case 3:
                            {
                                dongdang = CoreFunctions.MR_TinhSoLuongCosineSimilar(CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].Xuly_LayDanhSachGiaTriGiaoDich())
                                    , CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[j].Xuly_LayDanhSachGiaTriGiaoDich()), chuKy, minSimilar);
                                break;
                            }
                        default:
                            {
                                dongdang = CoreFunctions.MR_TinhSoLuongCosineSimilar(CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].Xuly_LayDanhSachGiaTongHop())
                                    , CoreFunctions.Tk_GetZScores((_danhSachCoPhieu[j].Xuly_LayDanhSachGiaTongHop())), chuKy, minSimilar);
                                break;
                            }
                    }
                    #endregion
                    if (dongdang < -1f)
                        dongdang = 0.0f;
                    result[i, j] = dongdang;
                    result[j, i] = dongdang;
                }
            }
            return result;
        }

        /// <summary>
        /// Tính ma trận đồng dạng của các cổ phiếu dựa trên Cosine.
        /// (Tham khảo ở hàm CoreFunction.MR_TinhSimilar_Delay)
        /// </summary>
        /// <param name="Case">
        /// 1: tính theo giá
        /// 2: tính theo khối lượng giao dịch
        /// 3: tính theo giá trị giao dịch
        /// Mặc định tính theo giá</param>
        /// <param name="chuKy"></param>
        /// <param name="minSimilar"></param>
        /// <param name="levelMatrix"></param>
        /// <returns></returns>
        public float[,] Xuly_TinhMaTranDongDang_DelayCosine(int Case, float minSimilar
            , out int levelMatrix, int lengthVector, int maxNumberDay)
        {
            /// Nếu các cổ phiếu có số ngày không bằng với số ngày giao dịch quy định thì nó sẽ không đồng dạng           
            levelMatrix = _danhSachCoPhieu.Count;
            float[,] result = new float[levelMatrix, levelMatrix];
            float dongdang = 0f;

            for (int i = 0; i < levelMatrix; i++)
            {
                result[i, i] = 1.0f;
                for (int j = 0; j < levelMatrix; j++)
                {
                    if (i != j)
                    {
                        #region *Case - Lựa chọn tham số để tính: giá, khối lượng giao dịch và giá trị giao dịch
                        switch (Case)
                        {
                            case 1:
                                {
                                    dongdang = CoreFunctions.MR_TinhSimilar_Delay(CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].DanhSachGiaDongCua)
                                        , CoreFunctions.Tk_GetZScores((_danhSachCoPhieu[j].DanhSachGiaDongCua)), lengthVector, maxNumberDay, minSimilar);
                                    break;
                                }
                            case 2:
                                {
                                    dongdang = CoreFunctions.MR_TinhSimilar_Delay(CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].DanhSachKhoiLuongGiaoDich)
                                        , CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[j].DanhSachKhoiLuongGiaoDich), lengthVector, maxNumberDay, minSimilar);
                                    break;
                                }
                            case 3:
                                {
                                    dongdang = CoreFunctions.MR_TinhSimilar_Delay(CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].Xuly_LayDanhSachGiaTriGiaoDich())
                                        , CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[j].Xuly_LayDanhSachGiaTriGiaoDich()), lengthVector, maxNumberDay, minSimilar);
                                    break;
                                }
                            default:
                                {
                                    dongdang = CoreFunctions.MR_TinhSimilar_Delay(CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[i].DanhSachGiaDongCua)
                                        , CoreFunctions.Tk_GetZScores(_danhSachCoPhieu[j].DanhSachGiaDongCua), lengthVector, maxNumberDay, minSimilar);
                                    break;
                                }
                        }
                        #endregion

                        result[i, j] = dongdang;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Chuyển đổi danh sách cluster chứa ID cổ phiếu thành list tên cổ phiếu theo mỗi cluster
        /// </summary>
        /// <param name="listClusterIdCP">danh sách cluster chứa các CP</param>
        /// <returns></returns>
        public List<List<string>> Xuly_ChuyenDoiListIDClusterSangListTenCoPhieu(List<List<int>> listClusterIdCP)
        {
            List<List<string>> result = new List<List<string>>();
            foreach (List<int> cluster in listClusterIdCP)
            {
                result.Add(new List<string>());
                foreach (int IdCoPhieu in cluster)
                    result[result.Count - 1].Add(_danhSachCoPhieu[IdCoPhieu].TenCoPhieu);
            }
            return result;
        }

        /// <summary>
        /// Tìm những cổ phiếu có danh sách ngày giao dịch không đầy đủ.
        /// </summary>
        /// <returns></returns>
        public List<string> Xuly_TimNhungCPDanhSachNgayGiaoDichKhongDayDu(out int soNgayGiaoDichDayDu)
        {
            List<string> listTenCP = new List<string>();

            /// Tìm danh sách giao dịch max.
            int max = CoreFunctions._listNgayGiaoDich.IndexOf(NgayBatDau) - CoreFunctions._listNgayGiaoDich.IndexOf(NgayKetThuc);
            if (max < 0)
                max = -max;
            max++;
            foreach (CoPhieu CP in _danhSachCoPhieu)
                if (CP.DanhSachNgayGiaoDich.Count < max)
                    listTenCP.Add(CP.TenCoPhieu);
            soNgayGiaoDichDayDu = max;

            return listTenCP;
        }

        /// <summary>
        /// Tính xu hướng thay đổi giá mỗi ngày của mỗi CP. 
        /// Không tính những CP có danh sách giao dịch không đầy đủ.
        /// </summary>
        /// <returns></returns>
        public List<List<float>> Xuly_TinhXuHuongTungNgayMoiCP(out List<string> listTenCP)
        {
            int max;
            List<float> listAvg = new List<float>();
            List<string> listCPGiaoDichKhongDu = this.Xuly_TimNhungCPDanhSachNgayGiaoDichKhongDayDu(out max);
            List<List<float>> result = new List<List<float>>();
            List<List<float>> listGiaThayDoiTungNgay = new List<List<float>>();
            listTenCP = new List<string>();

            foreach (CoPhieu CP in _danhSachCoPhieu)
                if (listCPGiaoDichKhongDu.Contains(CP.TenCoPhieu) == false)
                {
                    listGiaThayDoiTungNgay.Add(new List<float>());
                    listGiaThayDoiTungNgay[listGiaThayDoiTungNgay.Count - 1].AddRange(CP.DanhSachThayDoiGiaTongHopTungNgay);
                }

            for (int i = 0; i < max; i++)
                listAvg.Add(0.000f);

            max--;                                                                  /// Vì đây là danh sách thay đổi giá nên max giảm 1
            foreach (List<float> listValue in listGiaThayDoiTungNgay)
                for (int i = 0; i < max; i++)
                    listAvg[i] += listValue[i];

            for (int i = 0; i < max; i++)
                listAvg[i] = (float)Math.Round(listAvg[i] / listGiaThayDoiTungNgay.Count, 3);

            int count = 0;

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                result.Add(new List<float>());
                listTenCP.Add(CP.TenCoPhieu);
                if (!listCPGiaoDichKhongDu.Contains(CP.TenCoPhieu))
                {
                    for (int i = 0; i < max; i++)
                        result[result.Count - 1].Add((float)Math.Round(listGiaThayDoiTungNgay[count][i] - listAvg[i], 3));
                    count++;
                }
            }
            return result;
        }

        /// <summary>
        /// Tính xu hướng trung bình cho cổ phiếu nếu không có trả về -5f
        /// Xu hướng tính dựa trên thay đổi giá giao dịch
        /// </summary>
        /// <returns></returns>
        public List<float> Xuly_TinhXuHuongCP()
        {
            List<float> result = new List<float>();
            List<string> listTenCP;
            List<List<float>> listGiaThayDoi = this.Xuly_TinhXuHuongTungNgayMoiCP(out listTenCP);
            foreach (List<float> listValue in listGiaThayDoi)
                if (listValue.Count != 0)
                    listValue.Add(CoreFunctions.Tk_GetAverage(listValue));
                else
                    result.Add(-5.000f);
            return result;
        }

        /// <summary>
        /// Lấy danh sách tên CP với mức tăng trưởng tối thiểu
        /// </summary>
        /// <param name="minTangTruong">mức tăng trưởng tối thiểu</param>
        /// <returns></returns>
        public List<string> Xuly_LayDanhSachCPTangTruong(float minTangTruong)
        {
            List<string> result = new List<string>();
            foreach (CoPhieu CP in _danhSachCoPhieu)
                if (CP.TangTruongGia >= minTangTruong)
                    result.Add(CP.TenCoPhieu);
            return result;
        }

        public void Xuly_LoaiBoCacCPKhongPhaiBig4()
        {
            List<string> listBig4 = CoreFunctions.File_LoadBig4();
            for (int i = 0; i < _danhSachCoPhieu.Count; i++)
                if (listBig4.Contains(_danhSachCoPhieu[i].TenCoPhieu.ToUpper()) == false)
                {
                    _danhSachCoPhieu.RemoveAt(i);
                    i--;
                }
        }

        public void Xuly_LoaiBoKhongCoNgayGiaoDichMoiNhat_VNINDEX(int soNgayGiaoDichToiThieuGanNhat)
        {
            string datenew = "";
            foreach (CoPhieu cp in _danhSachCoPhieu)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    datenew = cp.DanhSachNgayGiaoDich_String[0];
                    break;
                }

            if (datenew != "")
                for (int i = 0; i < _danhSachCoPhieu.Count; i++)
                    if (_danhSachCoPhieu[i].DanhSachNgayGiaoDich_String[0] != datenew
                        || _danhSachCoPhieu[i].DanhSachNgayGiaoDich_String.Count < soNgayGiaoDichToiThieuGanNhat)
                    {
                        _danhSachCoPhieu.RemoveAt(i);
                        i--;
                    }
        }

        public void Xuly_FilterCp(float minGia, int minKhoiLuong, bool IsAND)
        {
            //minKhoiLuong /= 100;
            if (!IsAND)
            {
                for (int i = 0; i < _danhSachCoPhieu.Count; i++)
                    if (_danhSachCoPhieu[i].DanhSachGiaDongCua.Count <= 0 ||
                        _danhSachCoPhieu[i].GiaDongCuaTB10Ngay < minGia
                        || _danhSachCoPhieu[i].KhoiLuongTB10Ngay < minKhoiLuong)
                    {
                        _danhSachCoPhieu.RemoveAt(i);
                        i--;
                    }
            }
            else
            {
                for (int i = 0; i < _danhSachCoPhieu.Count; i++)
                    if (_danhSachCoPhieu[i].DanhSachGiaDongCua.Count <= 0 ||
                        _danhSachCoPhieu[i].GiaDongCuaTB10Ngay < minGia
                        && _danhSachCoPhieu[i].KhoiLuongTB10Ngay < minKhoiLuong)
                    {
                        _danhSachCoPhieu.RemoveAt(i);
                        i--;
                    }
            }
        }

        public void Xuly_FilterCp(uint GiaTriGiaoDich = 200000)
        {
            for (int i = 0; i < _danhSachCoPhieu.Count; i++)            
                if (_danhSachCoPhieu[i].GiaTriGiaoDich10Ngay < GiaTriGiaoDich)
                {
                    _danhSachCoPhieu.RemoveAt(i);
                    i--;
                }            
        }

        public DanhSachCoPhieu Xuly_LayDanhSachCoPhieu(int minIndex, int maxIndex)
        {
            DanhSachCoPhieu result = new DanhSachCoPhieu();
            foreach (CoPhieu cp in this._danhSachCoPhieu)
                if (cp.DanhSachGiaDongCua.Count > 0)
                    result._danhSachCoPhieu.Add(new CoPhieu(cp.TenCoPhieu, cp.GetDanhsachNgayGiaoDich(minIndex, maxIndex)));
            return result;
        }

        public void Xuly_LoadListZscore()
        {
            List<List<string>> listContent = CoreFunctions.File_LoadAnyFile(CoreFunctions._pathHOSE_HNX + @"\Testing_HubAuthorityPageRankToanBo_Delay.txt"
                , false, new string[] { "\t" });
            foreach (List<string> list in listContent)
                foreach (CoPhieu cp in _danhSachCoPhieu)
                    if (cp.TenCoPhieu.CompareTo(list[0].Trim()) == 0)
                    {
                        cp.Xuly_AddNewZscore(list[1], float.Parse(list[list.Count - 1]));
                        break;
                    }
            //foreach (CoPhieu cp in this._danhSachCoPhieu)            
            //    for (int i = cp.DanhsachZscore.Count + 1; i < cp.DanhSachNgayGiaoDich.Count; i++)                
            //        cp.Xuly_AddNewZscore(cp.DanhSachNgayGiaoDich_String[i], -10f);                
        }

        public List<int> Xuly_LayIndexTopNZScore(int n, int indexNgay)
        {
            List<int> listResult = new List<int>();
            int idmax = 0;
            for (int i = 0; i < n; i++)
            {
                idmax = 0;
                while (listResult.Contains(idmax) || this._danhSachCoPhieu[idmax].DanhsachZscore.Count <= indexNgay)
                    idmax++;

                for (int j = 1; j < this._danhSachCoPhieu.Count; j++)
                {
                    if (listResult.Contains(j) == false && this._danhSachCoPhieu[j].DanhsachZscore.Count > indexNgay
                        && this._danhSachCoPhieu[idmax].DanhsachZscore[indexNgay] < this._danhSachCoPhieu[j].DanhsachZscore[indexNgay])
                        idmax = j;
                }

                listResult.Add(idmax);
            }
            return listResult;
        }

        public float Xuly_TangTruongGia(List<string> listNameCP, List<float> listTile, string NgayBatDau, string NgayKetThuc)
        {
            ///NgayBatDau > NgayKetThuc
            float result = 0f;
            List<float> listValue = new List<float>();
            foreach (CoPhieu cp in _danhSachCoPhieu)
                if (listNameCP.Contains(cp.TenCoPhieu))
                    listValue.Add(cp.Xuly_TangTruongGiaDongCua(NgayBatDau, NgayKetThuc));

            for (int i = 0; i < listValue.Count; i++)
                result += listValue[i] * listTile[i];

            result = (float)Math.Round(result, 3);
            return result;
        }
        #endregion

        #region *** Kiemtra - Kiemtra_
        /// <summary>
        /// Kiểm tra danh sách cổ phiếu có chứa một cổ phiếu bất kỳ
        /// </summary>
        /// <param name="tenCophieu"></param>
        /// <returns>Nếu chứa: id của danh sách cổ phiếu. Ngược lại -1</returns>
        private int KiemTra_DanhSachCoPhieuChuaCoPhieu(string tenCophieu)
        {
            for (int i = 0; i < _danhSachCoPhieu.Count; i++)
                if (_danhSachCoPhieu[i].TenCoPhieu == tenCophieu)
                    return i;
            return -1;
        }

        public int KiemTra_SoNgayGiaoDich(string tenCP)
        {
            foreach (CoPhieu cp in _danhSachCoPhieu)
                if (cp.TenCoPhieu == tenCP)
                    return cp.DanhSachNgayGiaoDich.Count;
            return 0;
        }

        private void LoaiBoCoPhieuCoSoNgayGiaoDichDuoi15Ngay()
        {
            for (int i = 0; i < this._danhSachCoPhieu.Count; i++)
            {
                if (_danhSachCoPhieu[i].DanhSachGiaDongCua.Count < 15)
                {
                    _danhSachCoPhieu.RemoveAt(i);
                    i--;
                }
            }
        }
        #endregion

        #region *** Sapxep - Sapxep_
        /// <summary>
        /// Sắp xếp danh sách theo tên - ASC
        /// </summary>
        private void Sapxep_DanhSachCoPhieuTheoTen()
        {
            _danhSachCoPhieu.Sort(CoPhieu.CompareCoPhieu_TenCoPhieu_ASC);
        }
        #endregion

        #region *** Testing - Testing_

        #region * Testing Cắt lỗ chốt lời - Tcong
        /// <summary>
        /// Kiểm tra phần cắt lỗ - chốt lời. Kiểm tra thủ công khi nhập tham số xét trên 1 quãng thời gian đã xét trước
        /// Chỉ xét trên một kết quả cuối cùng: Tiền lời (không xét danh sách giao dịch)
        /// Ghi vào File: Testing_CatLoChotLoi_Original.txt
        /// </summary>
        /// <param name="soNgay">số ngày cách với điểm đảo chiều</param>
        /// <param name="soNgayT">số ngày T+X (quy định giao dịch CK)</param>
        /// <param name="phanTram">[0,100] phần trăm tăng của CP tính từ điểm đảo chiều </param>
        /// <param name="tiLeCatLo">[0,100] tỉ lệ cắt lỗ</param>
        /// <param name="tiLeChotLoi">[0,100] tỉ lệ chốt lời</param>
        public void Testing_CatLoChotLoi_Original(int soNgay, int soNgayT, float phanTram, float tiLeCatLo, float tiLeChotLoi)
        {
            List<string> listContent = new List<string>(); /// Dùng để ghi file
            listContent.Add(CoreFunctions.HeaderFile);

            string text = "So ngay cach dao chieu: " + soNgay.ToString() + " -- So ngay T: " + soNgayT.ToString() + " -- Phan tram cach dao chieu: " + phanTram + "%\r\n"
                + "Ti le Cat lo: " + tiLeCatLo.ToString() + "%\t" + "Ti le Chot Loi: " + tiLeChotLoi.ToString() + "%\r\n\r\n";
            text += "TenCoPhieu\tSLMua\tSLBan\t%Loi\tTienLoi";
            text += "\r\n----------------------------------------------------------------------";
            listContent.Add(text);

            float phanTramLoi, tienLoi;
            int solanMua, solanBan, soNgayGiaoDich = 0;
            string ngayBatDau = "", ngayKetThuc = "";

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                tienLoi = CP.Testing_CatLoChotLoi_Original(soNgay, soNgayT, phanTram, tiLeCatLo, tiLeChotLoi, out solanMua, out solanBan, out phanTramLoi);

                if (CP.TenCoPhieu.Length > 3)
                    text = CP.TenCoPhieu + "\t" + solanMua + "\t" + solanBan + "\t" + phanTramLoi.ToString() + "%\t" + tienLoi.ToString();
                else
                    text = CP.TenCoPhieu + "\t\t" + solanMua + "\t" + solanBan + "\t" + phanTramLoi.ToString() + "%\t" + tienLoi.ToString();

                if (tienLoi > 0 && phanTramLoi > 0)
                    text += "\t\t++";
                listContent.Add(text);

                if (soNgayGiaoDich < CP.DanhSachNgayGiaoDich.Count)
                {
                    soNgayGiaoDich = CP.DanhSachNgayGiaoDich.Count;
                    ngayBatDau = CoreFunctions.Xuly_ChuyenChuoiDataStock(CP.DanhSachNgayGiaoDich[0].NgayGiaoDich_Str);
                    ngayKetThuc = CoreFunctions.Xuly_ChuyenChuoiDataStock(CP.DanhSachNgayGiaoDich[soNgayGiaoDich - 1].NgayGiaoDich_Str);
                }
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_CatLoChotLoi_Original.txt", listContent);
        }

        /// <summary>
        /// Cải tiến hơn Testing_CatLoChotLoi_Original(...): khi vượt qua mức Chốt Lời vẫn tiếp tục duy trì cho tới khi gặp đỉnh đảo chiều tiếp theo
        /// </summary>
        /// <param name="soNgay"></param>
        /// <param name="soNgayT"></param>
        /// <param name="phanTram"></param>
        /// <param name="tiLeCatLo"></param>
        /// <param name="tiLeChotLoi"></param>
        public void Testing_CatLoChotLoi_Version1(int soNgay, int soNgayT, float phanTram, float tiLeCatLo, float tiLeChotLoi)
        {
            List<string> listContent = new List<string>(); /// Dùng để ghi file
            listContent.Add(CoreFunctions.HeaderFile);

            string text = "So ngay cach dao chieu: " + soNgay.ToString() + " -- So ngay T: " + soNgayT.ToString() + " -- Phan tram cach dao chieu: " + phanTram + "%\r\n"
                + "Ti le Cat lo: " + tiLeCatLo.ToString() + "%\t" + "Ti le Chot Loi: " + tiLeChotLoi.ToString() + "%\r\n\r\n";
            text += "TenCoPhieu\tSLMua\tSLBan\t%Loi\tTienLoi";
            text += "\r\n----------------------------------------------------------------------";
            listContent.Add(text);

            float phanTramLoi, tienLoi;
            int solanMua, solanBan, soNgayGiaoDich = 0;
            string ngayBatDau = "", ngayKetThuc = "";

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                tienLoi = CP.Testing_CatLoChotLoi_Version1(soNgay, soNgayT, phanTram, tiLeCatLo, tiLeChotLoi, out solanMua, out solanBan, out phanTramLoi);

                if (CP.TenCoPhieu.Length > 3)
                    text = CP.TenCoPhieu + "\t" + solanMua + "\t" + solanBan + "\t" + phanTramLoi.ToString() + "%\t" + tienLoi.ToString();
                else
                    text = CP.TenCoPhieu + "\t\t" + solanMua + "\t" + solanBan + "\t" + phanTramLoi.ToString() + "%\t" + tienLoi.ToString();

                if (tienLoi > 0 && phanTramLoi > 0)
                    text += "\t\t++";
                listContent.Add(text);

                if (soNgayGiaoDich < CP.DanhSachNgayGiaoDich.Count)
                {
                    soNgayGiaoDich = CP.DanhSachNgayGiaoDich.Count;
                    ngayBatDau = CoreFunctions.Xuly_ChuyenChuoiDataStock(CP.DanhSachNgayGiaoDich[0].NgayGiaoDich_Str);
                    ngayKetThuc = CoreFunctions.Xuly_ChuyenChuoiDataStock(CP.DanhSachNgayGiaoDich[soNgayGiaoDich - 1].NgayGiaoDich_Str);
                }
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_CatLoChotLoi_Version1.txt", listContent);
        }

        /// <summary>
        /// Cải tiến: sử dụng được đa hàm Testing_CatLoChotLoi (nhiều phiên bản). Thông qua biến Case 
        /// Lưu trữ nhiều tỉ lệ cắt lỗ - chốt lời qua danh sách Point. Không hiển thị số lần mua và số lần bán
        /// Chỉ ghi phần trăm lời trung bình. File: Testing_CatLoChotLoi_...txt (tùy vào Case sẽ có tên khác nhau)
        /// </summary>
        /// <param name="soNgay">số ngày cách với điểm đảo chiều</param>
        /// <param name="soNgayT">số ngày T+X (quy định giao dịch CK)</param>
        /// <param name="phanTram">[0,100] phần trăm tăng của CP tính từ điểm đảo chiều</param>
        /// <param name="listCatLoChotLoi">[0,100]Point(X:cắt lỗ,Y:chốt lời)</param>
        /// <param name="Case">
        /// 1: (default) cắt lỗ chốt lời Original
        /// 2: cắt lỗ chốt lời Version1
        /// </param>
        public void Testing_CatLoChotLoi_Function(int soNgay, int soNgayT, float phanTram, List<Point> listCatLoChotLoi, int Case)
        {
            List<string> listContent = new List<string>();                                                      /// Dùng để ghi file
            listContent.Add(CoreFunctions.HeaderFile);

            List<List<string>> listPhanTramLoi = new List<List<string>>();

            int soNgayGiaoDich = 0, soLanMua, soLanBan;
            string ngayBatDau = "", ngayKetThuc = "";
            float tiLeCatLo, tileChotLoi, phanTramLoi;

            foreach (CoPhieu CP in _danhSachCoPhieu)                                                            /// Khởi tạo listPhanTramLoi và header (số ngày giao dịch - bắt đầu và kết thúc)              
            {
                listPhanTramLoi.Add(new List<string>());
                listPhanTramLoi[listPhanTramLoi.Count - 1].Add(CP.TenCoPhieu);

                if (soNgayGiaoDich < CP.DanhSachNgayGiaoDich.Count)
                {
                    soNgayGiaoDich = CP.DanhSachNgayGiaoDich.Count;
                    ngayBatDau = CoreFunctions.Xuly_ChuyenChuoiDataStock(CP.DanhSachNgayGiaoDich[0].NgayGiaoDich_Str);
                    ngayKetThuc = CoreFunctions.Xuly_ChuyenChuoiDataStock(CP.DanhSachNgayGiaoDich[soNgayGiaoDich - 1].NgayGiaoDich_Str);
                }
            }

            string text = "So ngay cach dao chieu: " + soNgay.ToString() + " -- So ngay T: " + soNgayT.ToString() + " -- Phan tram cach dao chieu: " + phanTram + "%\r\n";
            text += "\r\nTenCoPhieu\t";

            foreach (Point capTiLeCatLoChotLoi in listCatLoChotLoi)
            {
                text += capTiLeCatLoChotLoi.X + "%-" + capTiLeCatLoChotLoi.Y + "%\t";
                tiLeCatLo = (float)capTiLeCatLoChotLoi.X;
                tileChotLoi = (float)capTiLeCatLoChotLoi.Y;

                #region - Switch - case lựa chọn hàm Testing_CatLoChotLoi
                switch (Case)
                {
                    case 1:                                                                                     /// Testing_CatLoChotLoi_Original(...)
                        {
                            for (int i = 0; i < _danhSachCoPhieu.Count; i++)
                            {
                                _danhSachCoPhieu[i].Testing_CatLoChotLoi_Original(soNgay, soNgayT, phanTram
                                    , tiLeCatLo, tileChotLoi, out soLanMua, out soLanBan, out phanTramLoi);

                                if (phanTramLoi > 5)
                                    listPhanTramLoi[i].Add(phanTramLoi.ToString() + "%+");
                                else
                                    listPhanTramLoi[i].Add(phanTramLoi.ToString() + "%");
                            }
                            break;
                        }
                    case 2:                                                                                     /// Testing_CatLoChotLoi_Version1(...)
                        {
                            for (int i = 0; i < _danhSachCoPhieu.Count; i++)
                            {
                                _danhSachCoPhieu[i].Testing_CatLoChotLoi_Version1(soNgay, soNgayT, phanTram
                                    , tiLeCatLo, tileChotLoi, out soLanMua, out soLanBan, out phanTramLoi);

                                if (phanTramLoi > 5)
                                    listPhanTramLoi[i].Add(phanTramLoi.ToString() + "%+");
                                else
                                    listPhanTramLoi[i].Add(phanTramLoi.ToString() + "%");
                            }
                            break;
                        }
                    default:                                                                                     /// Testing_CatLoChotLoi_Original(...)
                        {
                            for (int i = 0; i < _danhSachCoPhieu.Count; i++)
                            {
                                _danhSachCoPhieu[i].Testing_CatLoChotLoi_Original(soNgay, soNgayT, phanTram
                                    , tiLeCatLo, tileChotLoi, out soLanMua, out soLanBan, out phanTramLoi);

                                if (phanTramLoi > 5)
                                    listPhanTramLoi[i].Add(phanTramLoi.ToString() + "%+");
                                else
                                    listPhanTramLoi[i].Add(phanTramLoi.ToString() + "%");
                            }
                            break;
                        }
                }
                #endregion

            }
            text += "\r\n------------------------------------------------------------------------------------------------------------------------";
            listContent.Add(text);

            #region Chuyển đổi các giá trị từ listPhanTramLoi sang listContent
            foreach (List<string> listStr in listPhanTramLoi)
            {
                text = listStr[0] + "\t";
                if (listStr[0].Length <= 3)
                    text += "\t";

                for (int i = 1; i < listStr.Count; i++)
                    text += listStr[i] + "\t\t";
                listContent.Add(text);
            }

            text = "Testing_CatLoChotLoi_";
            switch (Case)
            {
                case 1: { text += "Original.txt"; break; }
                case 2: { text += "Version1.txt"; break; }
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);
            #endregion
        }

        public List<List<float>> Testing_TinhT_Cong(List<int> listNgayT)
        {
            List<string> listTCong = new List<string>();

            List<List<float>> listResult = new List<List<float>>();
            foreach (int i in listNgayT)
                listResult.Add(new List<float>());

            string text = "";
            float percent = 0;
            int count;
            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                count = 0;
                text = CP.TenCoPhieu + "\t\t" + CP.DanhSachGiaDongCua[0] + "\t\t";
                foreach (int Tcong in listNgayT)
                {
                    if (Tcong < CP.DanhSachNgayGiaoDich.Count)
                        percent = (float)Math.Log(CP.DanhSachGiaDongCua[0] / CP.DanhSachGiaDongCua[Tcong]);
                    else
                        percent = -9999;
                    percent = (float)Math.Round(percent * 100, 0);
                    listResult[count].Add(percent);
                    count++;

                    text += Math.Round(percent * 100, 0).ToString() + "\t\t";
                }
                listTCong.Add(text);
            }

            List<string> listContent = new List<string>();
            listContent.Add(this.HeaderFile);
            listContent.Add("\r\n");
            listContent.Add("T cong tinh theo gia dong cua");
            text = "CP" + "\t\t" + "Gia" + "\t\t";
            foreach (int Tcong in listNgayT)
                text += "T+" + Tcong.ToString() + "\t\t";
            listContent.Add(text);
            listContent.Add("--------------------------------------------------------");
            listContent.AddRange(listTCong);

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_TCong.txt", listContent);
            return listResult;
        }
        #endregion

        #region * Testing Markov Cluster
        /// <summary>
        /// Testing MarkovCluster
        /// </summary>
        /// <param name="Case">
        /// 1: cluster theo giá. 
        /// 2: cluster theo khối lượng giao dịch. 
        /// 3: cluster theo giá trị giao dịch</param>
        /// <param name="minSimilar">
        /// Độ đồng dạng tối thiểu giữa 2 phần tử trong ma trận
        /// </param>
        public List<List<string>> Testing_MarkovCluster(int Case, float minSimilar)
        {
            int levelMatrix, numberLoop, count;

            float[,] matrix = this.Xuly_TinhMaTranDongDang_TangGiamCungNhau(Case, out levelMatrix);
            //float[,] matrix = this.Xuly_TinhMaTranDongDang_Euclid_AvgStd(out levelMatrix);

            #region Tiền xử lý matrix
            for (int i = 0; i < levelMatrix; i++)
                for (int j = 0; j < levelMatrix; j++)
                    if (matrix[i, j] < minSimilar)
                        matrix[i, j] = 0f;
                    else
                        matrix[i, j] = 1f;            
            #endregion

            List<List<int>> listClusterIdCP = MarkovCluster.MarkovClusterAlgorithm(ref matrix, levelMatrix, out numberLoop, false, 2);

            /// Chuyển đổi id CP sang tên CP
            List<List<string>> listTenCP = this.Xuly_ChuyenDoiListIDClusterSangListTenCoPhieu(listClusterIdCP);

            /// Loại bỏ những cluster trùng nhau. Lưu giá trị các cluster bị trùng vào listRemove.
            bool flag;

            for (int i = 0; i < listTenCP.Count; i++)
                if (listTenCP[i].Count > 1)
                {
                    for (int j = 0; j < i; j++)
                        if (listTenCP[i].Count == listTenCP[j].Count)
                        {
                            flag = false;
                            count = listTenCP[i].Count;

                            for (int k = 0; k < count; k++)
                                if (listTenCP[i][k] != listTenCP[j][k])
                                {
                                    flag = true;
                                    break;
                                }

                            if (flag == false)
                            {
                                listTenCP.RemoveAt(i);
                                i--;
                                break;
                            }
                        }
                }
                else
                {
                    listTenCP.RemoveAt(i);
                    i--;
                }

            List<string> listContent = new List<string>();


            string text = "";
            count = 1;
            int count_row;
            for (int i = 0; i < listTenCP.Count; i++)
            {
                text = count + ":\t";
                count++;
                count_row = 0;
                foreach (string tenCP in listTenCP[i])
                {
                    count_row++;
                    if (count_row > 10)
                    {
                        listContent.Add(text);
                        text = (count - 1) + ":\t";
                        count_row = 0;
                    }
                    text += tenCP + "  ";
                }

                listContent.Add(text);
            }

            switch (Case)
            {
                case 1: { text = "Testing_MarkovCluster_Gia.txt"; break; }
                case 2: { text = "Testing_MarkovCluster_Khoiluong.txt"; break; }
                case 3: { text = "Testing_MarkovCluster_GiaTriGiaoDich.txt"; break; }
                default: { text = "Testing_MarkovCluster_Gia.txt"; break; }
            }

         
            listContent.Insert(0, "Dong dang toi thieu: " + minSimilar.ToString() + "\r\n");
            listContent.Insert(0, CoreFunctions.HeaderFile + "\r\n");

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);
            listContent.Add("\r\n--------------------------------------------------------------\r\n");
            CoreFunctions.File_AppendAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_MarkovCluster_Gia_LogCluster.txt", listContent);

            listContent = new List<string>();
            
            foreach (List<string> groupcp in listTenCP)
            {
                text ="";
                foreach (string cp in groupcp)
                    text += cp + "\t";
                if (text != "")
                {
                    listContent.Add(text);
                    listContent.Add("---");
                }                
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Chart_Group.txt", listContent);
            return listTenCP;
        }

        /// <summary>
        /// Testing độ đồng dạng tương lai sau khi thực hiện cluster        
        /// </summary>
        /// <param name="listClusterNameCP"></param>
        /// <returns></returns>
        public float Testing_MarkovCluster_KiemTraTuongLaiSimilarCosine_Gia(List<List<string>> listClusterNameCP)
        {
            List<List<float>> listGiaCluster = new List<List<float>>();
            List<float> listSimilarCosine = new List<float>();
            List<string> listContent = new List<string>();

            listContent.Add("Avg\t\tStd\t\tCoEff\t\tCluster");
            listContent.Add("--------------------------------------------------------------------------------------------\r\n");

            float result = 0.0f, coEff, avg, std;
            string text;
            int count = 0;
            foreach (List<string> cluster in listClusterNameCP)
                if (cluster.Count > 1)
                {
                    count++;
                    listGiaCluster = new List<List<float>>();

                    foreach (CoPhieu CP in _danhSachCoPhieu)                                /// lấy Zscore từ giá của các CP trong cluster
                        foreach (string nameCP in cluster)
                            if (CP.TenCoPhieu == nameCP)
                                listGiaCluster.Add(CoreFunctions.Tk_GetZScores(CP.Xuly_LayDanhSachGiaTongHop()));

                    listSimilarCosine = new List<float>();
                    for (int i = 0; i < listGiaCluster.Count; i++)
                        for (int j = i + 1; j < listGiaCluster.Count; j++)
                            listSimilarCosine.Add(CoreFunctions.MR_TinhCosineSimilar(listGiaCluster[i], listGiaCluster[j]));

                    avg = (float)Math.Round(CoreFunctions.Tk_GetAverage(listSimilarCosine), 3);
                    result += avg;

                    std = (float)Math.Round(CoreFunctions.Tk_PopularStandardDeviation(listSimilarCosine), 3);
                    coEff = (float)Math.Round(CoreFunctions.Tk_GetCoEfficentOfVariation(std, avg), 3);

                    text = avg + "\t\t" + std + "\t\t" + coEff + "\t\t";
                    foreach (string str in cluster)
                        text += str + "  ";
                    listContent.Add(text);
                }

            result = (float)Math.Round(result / count, 3);
            listContent.Add("\r\n-----------------------------");
            listContent.Add("Trung binh: " + result);

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_MarkovCluster_KiemTraTuongLaiSimilarCosine_Gia.txt", listContent);
            return result;
        }
        #endregion

        #region * Testing HITS - PageRank | Hub Score, Authority Score, PageRank
        /// <summary>
        /// Tính Hub Score. Nếu ma trận đồng dạng đối xứng thì Hub = Authority
        /// Hub Score: chứa nhiều link tham khảo đến các item uy tín
        /// Authority Score: uy tín khi có nhiều item khác tham khảo tới nó
        /// </summary>
        /// <param name="Case">
        /// 1: tính đồng dạng theo giá. 
        /// 2: tính đồng dạng theo khối lượng giao dịch.
        /// 3: tính đồng dạng theo giá trị giao dịch. </param>    
        /// <param name="SaiSo">Làm tròn bao nhiêu chữ số</param>
        public List<float> Testing_TinhHubScore(int Case, int SaiSo, float minSimilar)
        {
            List<float> listHub = new List<float>();
            string text = "";
            int levelMatrix;

            //float[,] matrix = Xuly_TinhMaTranDongDang_Cosine(Case, out levelMatrix);
            float[,] matrix = Xuly_TinhMaTranDongDang_TangGiamCungNhau(Case, out levelMatrix);
            matrix = CoreFunctions.Xuly_LoaiBoPhanTuItDongDang(matrix, levelMatrix, minSimilar, true);

            HIT.TinhHubScore(matrix, levelMatrix, SaiSo, out listHub);
            
            List<string> listContent = new List<string>();
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("Hub Score * 1000");
            listContent.Add("Sai so: " + SaiSo.ToString() + " -- Dong dang toi thieu: " + minSimilar.ToString() + "\r\n");
            listContent.Add("TenCP\t\tHub\t\tRanking");
            listContent.Add("-------------------------------------");

            for (int i = 0; i < listHub.Count; i++)
                listHub[i] = (float)Math.Round(listHub[i] * 1000, 3);

            List<int> listRanking = CoreFunctions.Xuly_TinhHangDanhSach(listHub, false);

            for (int i = 0; i < DanhSachCoPhieu_List.Count; i++)
            {
                text = DanhSachCoPhieu_List[i].TenCoPhieu;
                if (text.Length == 3)
                    text += "\t\t" + (listHub[i]);
                else
                    text += "\t" + (listHub[i]);

                if (listHub[i].ToString().Length > 5)
                    text += "\t" + listRanking[i];
                else
                    text += "\t\t" + listRanking[i];
                text += "*";                                                        /// Thêm dấu "*" để tìm trực tiếp trên file dễ hơn
                listContent.Add(text);
            }

            switch (Case)
            {
                case 1: { text = "Testing_HubScore_Gia.txt"; break; }
                case 2: { text = "Testing_HubScore_Khoiluong.txt"; break; }
                case 3: { text = "Testing_HubScore_GiaTriGiaoDich.txt"; break; }
                default:{ text = "Testing_HubScore_Gia.txt"; break; }
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);
            return listHub;
        }

        public List<float> Testing_TinhHubScore_Chuky(int Case, int SaiSo, float minSimilar, int chuky)
        {
            List<float> listHub = new List<float>();
            string text = "";
            int levelMatrix;

            float[,] matrix = Xuly_TinhMaTranDongDangChuKy_Cosine(Case, chuky, minSimilar, out levelMatrix);

            HIT.TinhHubScore(matrix, levelMatrix, SaiSo, out listHub);

            List<string> listContent = new List<string>();
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("Hub Score * 1000");
            listContent.Add("Sai so: " + SaiSo.ToString() + " -- Dong dang toi thieu: " + minSimilar.ToString() + " -- Chu ky: " + chuky + "\r\n");
            listContent.Add("TenCP\t\tHub\t\tRanking");
            listContent.Add("-------------------------------------");

            for (int i = 0; i < listHub.Count; i++)
                listHub[i] = (float)Math.Round(listHub[i] * 1000, 3);

            List<int> listRanking = CoreFunctions.Xuly_TinhHangDanhSach(listHub, false);

            for (int i = 0; i < DanhSachCoPhieu_List.Count; i++)
            {
                text = DanhSachCoPhieu_List[i].TenCoPhieu;
                if (text.Length == 3)
                    text += "\t\t" + (listHub[i]);
                else
                    text += "\t" + (listHub[i]);

                if (listHub[i].ToString().Length > 5)
                    text += "\t" + listRanking[i];
                else
                    text += "\t\t" + listRanking[i];
                text += "*";                                    /// thêm dấu "*" để dễ tìm kiếm theo hạng trực tiếp trên file
                listContent.Add(text);
            }

            switch (Case)
            {
                case 1: { text = "Testing_HubScoreChuKy_Gia.txt"; break; }
                case 2: { text = "Testing_HubScoreChuKy_Khoiluong.txt"; break; }
                case 3: { text = "Testing_HubScoreChuKy_GiaTriGiaoDich.txt"; break; }
                default: { text = "Testing_HubScoreChuKy_Gia.txt"; break; }
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);
            return listHub;
        }

        public void Testing_TinhHubAuthorityScore_Chuky(int Case, int SaiSo, float minSimilar, int chuky
            , ref List<float> listHub, ref List<float> listAuthority)
        {
            listHub = new List<float>();
            listAuthority = new List<float>();
            string text = "";
            int levelMatrix;

            float[,] matrix = Xuly_TinhMaTranDongDangChuKy_Cosine(Case, chuky, minSimilar, out levelMatrix);
         
            HIT.TinhHubAuthorityScore(matrix, levelMatrix, SaiSo, out listHub, out listAuthority);

            List<string> listContent = new List<string>();
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("Hub Score * 1000 || Authority * 1000");
            listContent.Add("Sai so: " + SaiSo.ToString() + " -- Dong dang toi thieu: " + minSimilar.ToString() + " -- Chu ky: " + chuky + "\r\n");
            listContent.Add("TenCP\t\tHub\t\tAuthority");
            listContent.Add("-------------------------------------");

            for (int i = 0; i < listHub.Count; i++)
            {
                listHub[i] = (float)Math.Round(listHub[i] * 1000, 3);
                listAuthority[i] = (float)Math.Round(listAuthority[i] * 1000, 3);
            }

            //List<int> listRanking = CoreFunctions.Xuly_TinhHangDanhSach(listHub, false);

            for (int i = 0; i < DanhSachCoPhieu_List.Count; i++)
            {
                text = DanhSachCoPhieu_List[i].TenCoPhieu;
                if (text.Length == 3)
                    text += "\t\t" + (listHub[i]);
                else
                    text += "\t" + (listHub[i]);

                if (listHub[i].ToString().Length > 5)
                    text += "\t" + listAuthority[i];
                else
                    text += "\t\t" + listAuthority[i];
                //text += "*";                                    /// thêm dấu "*" để dễ tìm kiếm theo hạng trực tiếp trên file
                listContent.Add(text);
            }

            switch (Case)
            {
                case 1: { text = "Testing_HubAuthorityScoreChuKy_Gia.txt"; break; }
                case 2: { text = "Testing_HubAuthorityScoreChuKy_Khoiluong.txt"; break; }
                case 3: { text = "Testing_HubAuthorityScoreChuKy_GiaTriGiaoDich.txt"; break; }
                default: { text = "Testing_HubAuthorityScoreChuKy_Gia.txt"; break; }
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);
        }

        /// <summary>
        /// Tính Hub, Authority Score
        /// (Tham khảo ở hàm CoreFunction.MR_TinhSimilar_Delay và DanhSachCoPhieu.uly_TinhMaTranDongDangChuKy_DelayCosine)
        /// </summary>
        /// <param name="Case"></param>
        /// <param name="SaiSo"></param>
        /// <param name="minSimilar"></param>
        /// <param name="lengthVector"></param>
        /// <param name="maxNumberDay"></param>
        /// <param name="listHub"></param>
        /// <param name="listAuthority"></param>
        public void Testing_TinhHubAuthorityScore_Delay(int Case, int SaiSo, float minSimilar, int lengthVector, int maxNumberDay
            , ref List<float> listHub, ref List<float> listAuthority)
        {
            listHub = new List<float>();
            listAuthority = new List<float>();
            string text = "";
            int levelMatrix;

            float[,] matrix = Xuly_TinhMaTranDongDang_DelayCosine(Case, minSimilar, out levelMatrix, lengthVector, maxNumberDay);

            HIT.TinhHubAuthorityScore(matrix, levelMatrix, SaiSo, out listHub, out listAuthority);

            List<string> listContent = new List<string>();
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("Hub Score * 1000 || Authority * 1000");
            listContent.Add("Sai so: " + SaiSo.ToString() + " -- Dong dang toi thieu: " + minSimilar.ToString() + "\r\n");
            listContent.Add("TenCP\t\tHub\t\tAuthority");
            listContent.Add("-------------------------------------");

            for (int i = 0; i < listHub.Count; i++)
            {
                listHub[i] = (float)Math.Round(listHub[i] * 1000, 3);
                listAuthority[i] = (float)Math.Round(listAuthority[i] * 1000, 3);
            }

            //List<int> listRanking = CoreFunctions.Xuly_TinhHangDanhSach(listHub, false);

            for (int i = 0; i < DanhSachCoPhieu_List.Count; i++)
            {
                text = DanhSachCoPhieu_List[i].TenCoPhieu;
                if (text.Length == 3)
                    text += "\t\t" + (listHub[i]);
                else
                    text += "\t" + (listHub[i]);

                if (listHub[i].ToString().Length > 5)
                    text += "\t" + listAuthority[i];
                else
                    text += "\t\t" + listAuthority[i];
                //text += "*";                                    /// thêm dấu "*" để dễ tìm kiếm theo hạng trực tiếp trên file
                listContent.Add(text);
            }

            switch (Case)
            {
                case 1: { text = "Testing_HubAuthorityScoreDelay_Gia.txt"; break; }
                case 2: { text = "Testing_HubAuthorityScoreDelay_Khoiluong.txt"; break; }
                case 3: { text = "Testing_HubAuthorityScoreDelay_GiaTriGiaoDich.txt"; break; }
                default: { text = "Testing_HubAuthorityScoreDelay_Gia.txt"; break; }
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);
        }

        public void Testing_TinhPageRank_Delay(int Case, int SaiSo, float minSimilar, int lengthVector, int maxNumberDay
            , ref List<float> listPageRank)
        {
            listPageRank = new List<float>();
            string text = "";
            int levelMatrix;

            float[,] matrix = Xuly_TinhMaTranDongDang_DelayCosine(Case, minSimilar, out levelMatrix, lengthVector, maxNumberDay);

            listPageRank.AddRange(PageRank.GetPageRank(matrix, levelMatrix, 0.5f));

            List<string> listContent = new List<string>();
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("PageRank Score * 1000");
            listContent.Add("Sai so: " + SaiSo.ToString() + " -- Dong dang toi thieu: " + minSimilar.ToString());
            listContent.Add("TenCP\t\tPageRank\t\tRanking");
            listContent.Add("-------------------------------------");

            for (int i = 0; i < listPageRank.Count; i++)
                listPageRank[i] = (float)Math.Round(listPageRank[i] * 1000, 3);

            List<int> listRanking = CoreFunctions.Xuly_TinhHangDanhSach(listPageRank, false);

            for (int i = 0; i < DanhSachCoPhieu_List.Count; i++)
            {
                text = DanhSachCoPhieu_List[i].TenCoPhieu;
                if (text.Length == 3)
                    text += "\t\t" + (listPageRank[i]);
                else
                    text += "\t" + (listPageRank[i]);

                if (listPageRank[i].ToString().Length > 5)
                    text += "\t" + listRanking[i];
                else
                    text += "\t\t" + listRanking[i];
                text += "*";                                    /// thêm dấu "*" để dễ tìm kiếm theo hạng trực tiếp trên file
                listContent.Add(text);
            }

            switch (Case)
            {
                case 1: { text = "Testing_PageRankDelay_Gia.txt"; break; }
                case 2: { text = "Testing_PageRankDelay_Khoiluong.txt"; break; }
                case 3: { text = "Testing_PageRankDelay_GiaTriGiaoDich.txt"; break; }
                default: { text = "Testing_PageRankDelay_Gia.txt"; break; }
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);

        }

        public void Testing_TinhPageRankToanBo_Delay(int Case, int Saiso, float minSimilar, int lengthVector, int maxNumberDay)
        {
            string text = "";
            List<string> listContent = new List<string>();
            List<List<float>> listResult = new List<List<float>>();
            List<float> result = new List<float>();
            DanhSachCoPhieu listPhu = new DanhSachCoPhieu();
            int min = 0, count = 0, levelMatrix;
            float[,] matrix = null;

            while (min < 500 && count < this._danhSachCoPhieu.Count)
            {
                foreach (CoPhieu cp in this._danhSachCoPhieu)
                {
                    if (cp.DanhSachNgayGiaoDich.Count <= min + lengthVector)
                    {
                        count++;
                        continue;
                    }

                    if (listPhu.DanhSachTenCoPhieu.Contains(cp.TenCoPhieu) == false)
                    {
                        listPhu._danhSachCoPhieu.Add(new CoPhieu(cp.TenCoPhieu, cp.GetDanhsachNgayGiaoDich(min, min + lengthVector)));
                        listResult.Add(new List<float>());
                    }
                    else
                    {
                        for (int i = 0; i < listPhu.DanhSachTenCoPhieu.Count; i++)
                            if (listPhu.DanhSachTenCoPhieu[i] == cp.TenCoPhieu)
                            {
                                /// code xử lý ở đây
                                listPhu._danhSachCoPhieu[i].Xuly_LoaiBoNgayGiaoDichGanNhat();

                                listPhu._danhSachCoPhieu[i].Xuly_ThemNgayGiaoDich(cp.DanhSachNgayGiaoDich[min + lengthVector]);

                                break;
                            }
                    }
                }

                matrix = listPhu.Xuly_TinhMaTranDongDang_Cosine(Case, out levelMatrix);
                for (int i = 0; i < levelMatrix; i++)
                    for (int j = 0; j < levelMatrix; j++)
                    {
                        matrix[i, j] += 0.9999f;
                    }

                ///matrix = listPhu.Xuly_TinhMaTranDongDang_DelayCosine(Case, minSimilar, out levelMatrix, lengthVector, maxNumberDay);


                result = new List<float>();
                result.AddRange(PageRank.GetPageRank(matrix, levelMatrix, 0.5f));

                for (int i = 0; i < result.Count; i++)
                    listResult[i].Add((float)Math.Round(result[i] * 1000, 2));

                min++;
            }

            for (int i = 0; i < listResult.Count; i++)
            {
                for (int j = 0; j < listResult[i].Count; j++)
                    listContent.Add(listPhu.DanhSachTenCoPhieu[i] + "\t" + listResult[i][j].ToString());
            }

            switch (Case)
            {
                case 1: { text = "Testing_PageRankAll_Gia.txt"; break; }
                case 2: { text = "Testing_PageRankAll_Khoiluong.txt"; break; }
                case 3: { text = "Testing_PageRankAll_GiatriGiaoDich.txt"; break; }
                default: { text = "Testing_PageRankAll_Gia.txt"; break; }
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);
        }

        public void Testing_TinhPageRankHubAuthority_ZscoreToanBo_Delay(float minSimilar, int lengthVector, int maxNumberDay)
        {
            #region Biến
            List<List<float>> listListResult = new List<List<float>>();
            List<List<float>> listResult = new List<List<float>>();
            List<List<float>> listList_Zscore;

            //List<float> result_Authority = new List<float>();
            //List<float> result_Hub = new List<float>();
            //List<float> result_PageRank = new List<float>();
            List<float> list_Zscore;      

            List<string> danhsachNgayGiaoDich = new List<string>();
            List<string> listContent = new List<string>();

            DanhSachCoPhieu listPhu = new DanhSachCoPhieu();
            int min = 0, count = 0;
            string row = "", text = "";
            #endregion

            foreach (CoPhieu cp in this._danhSachCoPhieu)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    danhsachNgayGiaoDich = cp.DanhSachNgayGiaoDich_String;
                    break;
                }
            
            while (min < 250 && count < this._danhSachCoPhieu.Count)
            {
                #region Lấy dữ liệu
                foreach (CoPhieu cp in this._danhSachCoPhieu)
                {
                    if (cp.DanhSachNgayGiaoDich.Count <= min + lengthVector)
                    {
                        count++;
                        continue;
                    }

                    if (listPhu.DanhSachTenCoPhieu.Contains(cp.TenCoPhieu) == false)
                    {
                        listPhu._danhSachCoPhieu.Add(new CoPhieu(cp.TenCoPhieu, cp.GetDanhsachNgayGiaoDich(min, min + lengthVector)));
                        listResult.Add(new List<float>());
                    }
                    else
                        for (int i = 0; i < listPhu.DanhSachTenCoPhieu.Count; i++)
                            if (listPhu.DanhSachTenCoPhieu[i] == cp.TenCoPhieu)
                            {
                                /// code xử lý ở đây
                                listPhu._danhSachCoPhieu[i].Xuly_LoaiBoNgayGiaoDichGanNhat();
                                listPhu._danhSachCoPhieu[i].Xuly_ThemNgayGiaoDich(cp.DanhSachNgayGiaoDich[min + lengthVector]);
                                break;
                            }
                }           
              
                listPhu.Xuly_FilterCp(7, 20000, false);
                listPhu.Sort_TenCoPhieu_ASC();
                #endregion

                listListResult = listPhu.Testing_TinhHubAuthorityPageRank_Delay_Gia(6, 0.9f, 60, 30);

                #region Điều chỉnh dữ liệu - Tính ZScore

                listList_Zscore = new List<List<float>>();
                list_Zscore = new List<float>();
                
                for (int i = 0; i < 3; i++)
                    listList_Zscore.Add(CoreFunctions.Tk_GetZScores(listListResult[i]));

                for (int i = 0; i < listListResult[0].Count; i++)
                    list_Zscore.Add((float)Math.Round(listList_Zscore[0][i] + listList_Zscore[1][i] + listList_Zscore[2][i], 2));

                for (int i = 0; i < listListResult[0].Count; i++)
                {
                    row = listPhu.DanhSachTenCoPhieu[i]
                          + "\t" + danhsachNgayGiaoDich[min]
                          + "\t" + Math.Round(listList_Zscore[0][i], 2).ToString()
                          + "\t" + Math.Round(listList_Zscore[1][i], 2).ToString()
                          + "\t" + Math.Round(listList_Zscore[2][i], 2).ToString()
                          + "\t" + list_Zscore[i];
                    listContent.Add(row);
                }
           
                #endregion

                min++;
            }

            listContent.Insert(0, "CP\tNgayGD\tHub\tAuth\tPage\tZscore");

            text ="Testing_HubAuthorityPageRankToanBo_Delay.txt";

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);
        }

        public void Testing_TinhHubAuthorityPageRank_Delay(int Case, int SaiSo, float minSimilar, int lengthVector, int maxNumberDay
           , ref List<float> listHub, ref List<float> listAuthority, ref List<float> listPageRank)
        {
            listHub = new List<float>();
            listAuthority = new List<float>();
            listPageRank = new List<float>();
            string text = "";
            int levelMatrix;

            float[,] matrix = Xuly_TinhMaTranDongDang_DelayCosine(Case, minSimilar, out levelMatrix, lengthVector, maxNumberDay);

            HIT.TinhHubAuthorityScore(matrix, levelMatrix, SaiSo, out listHub, out listAuthority);
            listPageRank.AddRange(PageRank.GetPageRank(matrix, levelMatrix, 0.5f));

            List<string> listContent = new List<string>();
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("Hub Score * 1000 & Authority * 1000 & PageRank * 1000");
            listContent.Add("Sai so: " + SaiSo.ToString() + " -- Dong dang toi thieu: " + minSimilar.ToString() + "\r\n");
            listContent.Add("TenCP\t\tHub\t\tAuthority\tPageRank");
            listContent.Add("-------------------------------------");

            for (int i = 0; i < listHub.Count; i++)
            {
                listHub[i] = (float)Math.Round(listHub[i] * 1000, 3);
                listAuthority[i] = (float)Math.Round(listAuthority[i] * 1000, 3);
                listPageRank[i] = (float)Math.Round(listPageRank[i] * 1000, 3);
            }

            for (int i = 0; i < DanhSachCoPhieu_List.Count; i++)
            {
                text = DanhSachCoPhieu_List[i].TenCoPhieu;
                if (text.Length == 3)
                    text += "\t\t" + (listHub[i]);
                else
                    text += "\t" + (listHub[i]);

                if (listHub[i].ToString().Length > 6)
                    text += "\t" + listAuthority[i];
                else
                    text += "\t\t" + listAuthority[i];

                if (listPageRank[i].ToString().Length > 6)
                    text += "\t" + listPageRank[i];
                else
                    text += "\t\t" + listPageRank[i];

                listContent.Add(text);
            }

            switch (Case)
            {
                case 1: { text = "Testing_HubAuthorityPageRankDelay_Gia.txt"; break; }
                case 2: { text = "Testing_HubAuthorityPageRankDelay_Khoiluong.txt"; break; }
                case 3: { text = "Testing_HubAuthorityPageRankDelay_GiaTriGiaoDich.txt"; break; }
                default: { text = "Testing_HubAuthorityPageRankDelay_Gia.txt"; break; }
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);
        }

        public List<List<float>> Testing_TinhHubAuthorityPageRank_Delay_Gia_KhoiLuong(int SaiSo, float minSimilar, int lengthVector, int maxNumberDay)
        {
            List<List<float>> listResult = new List<List<float>>();
            List<float> listHub_gia = new List<float>();
            List<float> listAuthority_gia = new List<float>();
            List<float> listPageRank_gia = new List<float>();

            List<float> listHub_khoiluong = new List<float>();
            List<float> listAuthority_khoiluong = new List<float>();
            List<float> listPageRank_khoiluong = new List<float>();

            string text = "";
            int levelMatrix;

            float[,] matrix_gia = Xuly_TinhMaTranDongDang_DelayCosine(1, minSimilar, out levelMatrix, lengthVector, maxNumberDay);
            float[,] matrix_khoiluong = Xuly_TinhMaTranDongDang_DelayCosine(2, minSimilar, out levelMatrix, lengthVector, maxNumberDay);

            HIT.TinhHubAuthorityScore(matrix_gia, levelMatrix, SaiSo, out listHub_gia, out listAuthority_gia);
            listPageRank_gia.AddRange(PageRank.GetPageRank(matrix_gia, levelMatrix, 0.5f));

            HIT.TinhHubAuthorityScore(matrix_khoiluong, levelMatrix, SaiSo, out listHub_khoiluong, out listAuthority_khoiluong);
            listPageRank_khoiluong.AddRange(PageRank.GetPageRank(matrix_khoiluong, levelMatrix, 0.5f));

            List<string> listContent = new List<string>();
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("Hub Score * 1000 & Authority * 1000 & PageRank * 1000");
            listContent.Add("Sai so: " + SaiSo.ToString() + " -- Dong dang toi thieu: " + minSimilar.ToString() + "\r\n");
            listContent.Add("TenCP\tH.Gia\tA.Gia\tPR.Gia\tH.Kl\tA.Kl\tPR.Kl");
            listContent.Add("-------------------------------------");

            for (int i = 0; i < listHub_gia.Count; i++)
            {
                listHub_gia[i] = (float)Math.Round(listHub_gia[i] * 1000, 2);
                listAuthority_gia[i] = (float)Math.Round(listAuthority_gia[i] * 1000, 2);
                listPageRank_gia[i] = (float)Math.Round(listPageRank_gia[i] * 1000, 2);

                listHub_khoiluong[i] = (float)Math.Round(listHub_khoiluong[i] * 1000, 2);
                listAuthority_khoiluong[i] = (float)Math.Round(listAuthority_khoiluong[i] * 1000, 2);
                listPageRank_khoiluong[i] = (float)Math.Round(listPageRank_khoiluong[i] * 1000, 2);
            }

            for (int i = 0; i < DanhSachCoPhieu_List.Count; i++)
            {
                text = DanhSachCoPhieu_List[i].TenCoPhieu;
                if (listHub_gia[i] > 0.5f && listHub_khoiluong[i] > 0.5f
                    && listAuthority_khoiluong[i] > 0.5f && listAuthority_gia[i] > 0.5f
                    && listPageRank_khoiluong[i] > 0.5f && listPageRank_gia[i] > 0.5f)
                    text += "*\t";
                else
                    text += "\t";
                text += listHub_gia[i] + "\t" + listAuthority_gia[i] + "\t" + listPageRank_gia[i]
                    + "\t" + listHub_khoiluong[i] + "\t" + listAuthority_khoiluong[i] + "\t" + listPageRank_khoiluong[i];

                listContent.Add(text);
            }

            text = "Testing_HubAuthorityPageRankDelay_GiaKhoiLuong.txt";
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);

            listResult.Add(listHub_gia);
            listResult.Add(listAuthority_gia);
            listResult.Add(listPageRank_gia);

            listResult.Add(listHub_khoiluong);
            listResult.Add(listAuthority_khoiluong);
            listResult.Add(listPageRank_khoiluong);

            return listResult;
        }

        public List<List<float>> Testing_TinhHubAuthorityPageRank_Delay_Gia(int SaiSo, float minSimilar, int lengthVector, int maxNumberDay)
        {
            List<List<float>> listResult = new List<List<float>>();
            List<float> listHub_gia = new List<float>();
            List<float> listAuthority_gia = new List<float>();
            List<float> listPageRank_gia = new List<float>();

            string text = "";
            int levelMatrix;

            float[,] matrix_gia = Xuly_TinhMaTranDongDang_DelayCosine(1, minSimilar, out levelMatrix, lengthVector, maxNumberDay);
            if (levelMatrix == 0)
                return null;

            HIT.TinhHubAuthorityScore(matrix_gia, levelMatrix, SaiSo, out listHub_gia, out listAuthority_gia);
            listPageRank_gia.AddRange(PageRank.GetPageRank(matrix_gia, levelMatrix, 0.5f));

            List<string> listContent = new List<string>();
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("Hub Score * 1000 & Authority * 1000 & PageRank * 1000");
            listContent.Add("Sai so: " + SaiSo.ToString() + " -- Dong dang toi thieu: " + minSimilar.ToString() + "\r\n");
            listContent.Add("TenCP\tH.Gia\tA.Gia\tPR.Gia");
            listContent.Add("-------------------------------------");

            for (int i = 0; i < listHub_gia.Count; i++)
            {
                listHub_gia[i] = (float)Math.Round(listHub_gia[i] * 1000, 2);
                listAuthority_gia[i] = (float)Math.Round(listAuthority_gia[i] * 1000, 2);
                listPageRank_gia[i] = (float)Math.Round(listPageRank_gia[i] * 1000, 2);
            }

            for (int i = 0; i < DanhSachCoPhieu_List.Count; i++)
            {
                text = DanhSachCoPhieu_List[i].TenCoPhieu + "\t";

                text += listHub_gia[i] + "\t" + listAuthority_gia[i] + "\t" + listPageRank_gia[i];

                listContent.Add(text);
            }

            text = "Testing_HubAuthorityPageRankDelay_Gia.txt";
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listContent);

            listResult.Add(listHub_gia);
            listResult.Add(listAuthority_gia);
            listResult.Add(listPageRank_gia);

            return listResult;
        }
        #endregion

        #region * Testing Tìm kiếm sự giống nhau ở quá khứ với những CP khác
        /// <summary>
        /// Testing tìm kiếm 1 đoạn thời giá giống nhau và từ đó lưu lại các thay đổi giá
        /// Hàm này được dùng khi load đầy đủ giá ở quá khứ
        /// </summary>
        /// <param name="listGiaCanTim">danh sách giá cần so khớp</param>
        /// <param name="ngayBatDau">ngày bắt đầu của thời giá đầu vào</param>
        /// <param name="minSimilar">tỉ lệ đồng dạng tối thiểu</param>
        /// <param name="soNgay">số ngày cách điểm đang xét</param>
        /// <param name="listGiaThayDoi">lưu lại các thay đổi của thời giá</param>
        /// <param name="listNgayBatDauGiongNhau">lưu lại các ngày bắt đầu mà có thời giá giống nhau</param>
        /// <param name="listNgayKetThucGiongNhau">lưu lại các ngày kết thúc mà có thời giá giống nhau</param>
        /// <param name="listNameCP">lưu lại tên các CP có quá khứ giống nhau</param>
        /// <param name="listCosineSimilar">lưu lại độ đồng dạng của các kết quả so khớp</param>
        private void Testing_TimKiemSuGiongNhauQuaKhu(List<float> listGiaCanTim, string ngayBatDau, float minSimilar, int soNgay
            , out List<List<float>> listGiaThayDoi, out List<string> listNgayBatDauGiongNhau
            , out List<string> listNgayKetThucGiongNhau, out List<string> listNameCP, out List<float> listCosineSimilar)
        {
            List<float> listZcoreGiaCanTim = CoreFunctions.Tk_GetZScores(listGiaCanTim);
            List<float> listGiaCoPhieu;
            List<float> listKhoangThoiGian;

            int doDaiThoiGianCanTim = listGiaCanTim.Count;
            int idBatDau = CoreFunctions._listNgayGiaoDich.IndexOf(ngayBatDau);

            float cosineSimilar;

            listGiaThayDoi = new List<List<float>>();
            listNgayBatDauGiongNhau = new List<string>();
            listNgayKetThucGiongNhau = new List<string>();
            listNameCP = new List<string>();
            listCosineSimilar = new List<float>();

            if (doDaiThoiGianCanTim < soNgay)
                return;

            foreach (CoPhieu CP in _danhSachCoPhieu)                                    /// danh sách giá full
            {
                listGiaCoPhieu = CP.Xuly_LayDanhSachGiaTongHop();                       /// Lấy danh sách giá tổng hợp của cổ phiếu                               

                if (listGiaCoPhieu.Count < 100)                                         /// CP xem xét quá khứ phải có tối thiểu 100 ngày giao dịch
                    continue;

                for (int i = idBatDau + soNgay + 1; i < listGiaCoPhieu.Count; i++)      /// bắt đầu xét cách khoảng với độ dài ở tương lai để xét kết quả
                {
                    listKhoangThoiGian = new List<float>();
                    for (int j = i; j < listGiaCoPhieu.Count; j++)                      /// rút 1 đoạn thời giá của cổ phiếu với độ dài tương ứng thời giá đưa vào
                        if (listKhoangThoiGian.Count < doDaiThoiGianCanTim)
                            listKhoangThoiGian.Add(listGiaCoPhieu[j]);
                        else
                            break;

                    if (listKhoangThoiGian.Count == doDaiThoiGianCanTim)                /// Chỉ xử lý khi đoạn thời giá rút ra có độ dài bằng với thời giá đưa vào
                    {
                        cosineSimilar = CoreFunctions.MR_TinhCosineSimilar(CoreFunctions.Tk_GetZScores(listKhoangThoiGian), listZcoreGiaCanTim);
                        if (cosineSimilar >= minSimilar)
                        {
                            listNgayBatDauGiongNhau.Add(CoreFunctions._listNgayGiaoDich[i]);
                            listNgayKetThucGiongNhau.Add(CoreFunctions._listNgayGiaoDich[i + doDaiThoiGianCanTim - 1]);
                            listNameCP.Add(CP.TenCoPhieu);
                            listCosineSimilar.Add(cosineSimilar);

                            listGiaThayDoi.Add(new List<float>());
                            for (int k = i - soNgay; k < i; k++)
                                listGiaThayDoi[listGiaThayDoi.Count - 1].Add(listGiaCoPhieu[k]);

                            i = i + doDaiThoiGianCanTim - 1;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Testing tìm kiếm 1 đoạn giá trị float (giá - khối lượng - giá trị giao dịch) tìm kiếm sự giống nhau trong quá khứ. 
        /// Hàm này được dùng khi load đầy đủ file ở quá khứ
        /// </summary>
        /// <param name="listGiaCanTim">danh sách float cần so khớp</param>
        /// <param name="Case">1:Giá - 2:Khối lượng - 3:Giá trị giao dịch</param>
        /// <param name="ngayBatDau">ngày bắt đầu của giá trị đầu vào</param>
        /// <param name="minSimilar">tỉ lệ đồng dạng tối thiệu</param>
        /// <param name="soNgay">số ngày cách điểm đang xét</param>
        /// <param name="listGiaThayDoi">lưu lại các thay đổi sau khi so khớp</param>
        /// <param name="listNgayBatDauGiongNhau">lưu lại các ngày bắt đầu mà có thời giá giống nhau</param>
        /// <param name="listNgayKetThucGiongNhau">lưu lại các ngày kết thúc mà có thời giá giống nhau</param>
        /// <param name="listNameCP">lưu lại tên các CP có quá khứ giống nhau</param>
        /// <param name="listCosineSimilarGia">lưu lại độ đồng dạng của các kết quả so khớp</param>
        /// <param name="listCosineSimilarKhoiLuong">lưu lại độ đồng dạng về khối lượng của các kết quả so khớp</param>
        private void Testing_TimKiemSuGiongNhauQuaKhu(List<float> listGiaCanTim, List<float> listKhoiLuongCanTim, int chuky, string ngayBatDau, float minSimilar, int soNgay
            , out List<List<float>> listGiaThayDoi, out List<string> listNgayBatDauGiongNhau, out List<string> listNgayKetThucGiongNhau
            , out List<string> listNameCP, out List<float> listCosineSimilarGia, out List<float> listCosineSimilarKhoiLuong)
        {
            List<float> listZscoreGiaCanTim = CoreFunctions.Tk_GetZScores(listGiaCanTim);
            List<float> listZscoreKhoiLuongCanTim = CoreFunctions.Tk_GetZScores(listKhoiLuongCanTim);
            List<float> listGiaCoPhieu;
            List<int> listKhoiLuong;
            List<float> listKhoangThoiGian;
            List<float> listKhoangThoiGianKhoiLuong;
            List<float> listTam;
            List<float> listTamKhoiLuong;
            int doDaiThoiGianCanTim = listGiaCanTim.Count;
            int idBatDau = CoreFunctions._listNgayGiaoDich.IndexOf(ngayBatDau);
            int temp;
            float cosineSimilar;

            listGiaThayDoi = new List<List<float>>();
            listNgayBatDauGiongNhau = new List<string>();
            listNgayKetThucGiongNhau = new List<string>();
            listNameCP = new List<string>();
            listCosineSimilarGia = new List<float>();
            listCosineSimilarKhoiLuong = new List<float>();
            listGiaCoPhieu = new List<float>();
            listKhoiLuong = new List<int>();

            if (doDaiThoiGianCanTim < soNgay)
                return;

            foreach (CoPhieu CP in _danhSachCoPhieu)                                    /// danh sách giá trị full
            {
                listGiaCoPhieu = CP.Xuly_LayDanhSachGiaTongHop();
                listKhoiLuong = CP.DanhSachKhoiLuongGiaoDich_Int;

                for (int i = idBatDau + soNgay + 1; i < listGiaCoPhieu.Count; i++)      /// bắt đầu xét cách khoảng với độ dài ở tương lai để xét kết quả
                {
                    listKhoangThoiGian = new List<float>();
                    listKhoangThoiGianKhoiLuong = new List<float>();

                    for (int j = i; j < listGiaCoPhieu.Count; j = j + chuky)            /// rút 1 đoạn thời giá của cổ phiếu với độ dài tương ứng thời giá đưa vào
                    {
                        listTam = new List<float>();
                        listTamKhoiLuong = new List<float>();
                        for (int k = 0; k < chuky; k++)
                        {
                            if (j + k < listGiaCoPhieu.Count)
                            {
                                listTam.Add(listGiaCoPhieu[j + k]);
                                listTamKhoiLuong.Add(listKhoiLuong[j + k]);
                            }

                            if (listKhoangThoiGian.Count < doDaiThoiGianCanTim)
                            {
                                listKhoangThoiGian.Add(CoreFunctions.Tk_GetAverage(listTam));
                                listKhoangThoiGianKhoiLuong.Add(CoreFunctions.Tk_GetAverage(listTamKhoiLuong));
                            }
                            else
                                break;
                        }

                        if (listKhoangThoiGian.Count >= doDaiThoiGianCanTim)
                            break;
                    }

                    if (listKhoangThoiGian.Count == doDaiThoiGianCanTim)                /// Chỉ xử lý khi đoạn thời giá rút ra có độ dài bằng với thời giá đưa vào
                    {
                        cosineSimilar = CoreFunctions.MR_TinhCosineSimilar(CoreFunctions.Tk_GetZScores(listKhoangThoiGian), listZscoreGiaCanTim);
                        if (cosineSimilar >= minSimilar)
                        {
                            listNgayBatDauGiongNhau.Add(CoreFunctions._listNgayGiaoDich[i]);
                            listNgayKetThucGiongNhau.Add(CoreFunctions._listNgayGiaoDich[i + doDaiThoiGianCanTim - 1]);
                            listNameCP.Add(CP.TenCoPhieu);
                            cosineSimilar = (float)Math.Round(cosineSimilar, 3);
                            listCosineSimilarGia.Add(cosineSimilar);

                            cosineSimilar = CoreFunctions.MR_TinhCosineSimilar(CoreFunctions.Tk_GetZScores(listKhoangThoiGianKhoiLuong), listZscoreKhoiLuongCanTim);
                            cosineSimilar = (float)Math.Round(cosineSimilar, 3);
                            listCosineSimilarKhoiLuong.Add(cosineSimilar);

                            listGiaThayDoi.Add(new List<float>());

                            temp = i - soNgay;
                            if (temp < 0)
                                temp = 0;
                            for (int k = temp; k < i; k++)
                            {
                                listTam = new List<float>();
                                for (int g = 0; g < chuky; g++)
                                    if (k + g < i)
                                        listTam.Add(listGiaCoPhieu[k + g]);
                                    else
                                        break;

                                listGiaThayDoi[listGiaThayDoi.Count - 1].Add(CoreFunctions.Tk_GetAverage(listTam));
                            }

                            i = i + doDaiThoiGianCanTim - 1;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Testing tìm kiếm 1 đoạn thời giá giống nhau và từ đó lưu lại các thay đổi giá tương lai (ở đoạn giống nhau). 
        /// Hàm ngày được dùng khi load đầy đủ giá ở quá khứ. Xét trên danh sách các List đây vào
        /// Lưu thành file Testing_TimKiemSuGiongNhauQuaKhu_ListCP.txt
        /// </summary>
        /// <param name="listTenCPCanTim"></param>
        /// <param name="chuky"></param>
        /// <param name="ngayBatDau"></param>
        /// <param name="ngayKetThuc"></param>
        /// <param name="minSimilar"></param>
        /// <param name="soNgay"></param>
        public void Testing_TimKiemSuGiongNhauQuaKhu_DanhSachTenCp(List<string> listTenCPCanTim, DanhSachCoPhieu danhSachCP, int[] chuky, string ngayBatDau, string ngayKetThuc, float minSimilarGia, float minSimilarKhoiLuong, int soNgay)
        {
            listTenCPCanTim.Sort();
            int idCp = 0;
            float thaydoiGia;
            List<string> listContent = new List<string>();
            List<string> listNgayBatDau = new List<string>();
            List<string> listNgayKetThuc = new List<string>();
            List<string> listTenCP = new List<string>();
            List<List<float>> listGiaThayDoi = new List<List<float>>();
            List<float> listCosineGia = new List<float>();
            List<float> listCosineKhoiLuong = new List<float>();
            List<float> listGiaTongHop = new List<float>();
            List<float> listKhoiLuong = new List<float>();

            string text = "Khoang thoi gian dua vao:: Ngay bat dau: " + ngayBatDau + " -- Ngay ket thuc: " + ngayKetThuc;
            string chukystr = "";
            foreach (int i in chuky)
                chukystr += i + "; ";
            listContent.Add(text);
            listContent.Add("Dong dang gia toi thieu: " + minSimilarGia + " -- Khoang cach ngay thay doi gia: " + soNgay + " -- Chu ky:" + chukystr);
            listContent.Add("Dong dang khoi luong toi thieu: " + minSimilarKhoiLuong + "\r\n");
            listContent.Add("CPGoc\t\tCPQuaKhu\tNgayBatDau\t\tNgayKetThuc\t\tCosineGia\t\tCosineKhoiLuong\t\tThayDoiGia");
            listContent.Add("--------------------------------------------------------------------------------------------------------------------------------------------------------");

            foreach (string tenCP in listTenCPCanTim)
                for (int i = idCp; i < danhSachCP._danhSachCoPhieu.Count; i++)
                    if (danhSachCP._danhSachCoPhieu[i].TenCoPhieu == tenCP)
                    {
                        listGiaTongHop = danhSachCP._danhSachCoPhieu[i].Xuly_LayDanhSachGiaTongHop();
                        listKhoiLuong = danhSachCP._danhSachCoPhieu[i].DanhSachKhoiLuongGiaoDich;
                        foreach (int motchuky in chuky)
                        {
                            this.Testing_TimKiemSuGiongNhauQuaKhu(listGiaTongHop, listKhoiLuong, motchuky, ngayBatDau, minSimilarGia, soNgay, out listGiaThayDoi
                                , out listNgayBatDau, out listNgayKetThuc, out listTenCP, out listCosineGia, out listCosineKhoiLuong);

                            for (int j = 0; j < listGiaThayDoi.Count; j++)
                            {
                                if (listCosineKhoiLuong[j] >= minSimilarKhoiLuong)
                                {
                                    thaydoiGia = (float)Math.Round(Math.Log(listGiaThayDoi[j][0] / listGiaThayDoi[j][listGiaThayDoi[j].Count - 1]), 3);

                                    text = tenCP + CoreFunctions.Xuly_ChuoiTraVe(tenCP, 3, 2, 1, "\t");
                                    text += listTenCP[j] + CoreFunctions.Xuly_ChuoiTraVe(listTenCP[j], 3, 2, 1, "\t");
                                    text += listNgayBatDau[j] + "\t\t" + listNgayKetThuc[j] + "\t\t";
                                    text += listCosineGia[j] + CoreFunctions.Xuly_ChuoiTraVe(listCosineGia[j].ToString(), 5, 3, 2, "\t");
                                    text += listCosineKhoiLuong[j] + CoreFunctions.Xuly_ChuoiTraVe(listCosineKhoiLuong[j].ToString(), 5, 4, 3, "\t");
                                    text += thaydoiGia;

                                    listContent.Add(text);
                                }
                            }
                        }
                        listContent.Add("");

                        idCp = i;
                        break;
                    }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_TimKiemSuGiongNhauQuaKhu_ListCP.txt", listContent);
        }

        /// <summary>
        /// Testing tìm kiếm 1 đoạn thời giá giống nhau và từ đó lưu lại các thay đổi giá tương lai (ở đoạn giống nhau). 
        /// Hàm ngày được dùng khi load đầy đủ giá ở quá khứ. 
        /// Lưu thành file Testing_TimKiemSuGiongNhauQuaKhu_ToanBoCP.txt
        /// </summary>
        /// <param name="danhSachCP">danh sách CP cần tìm quá khứ giống nhau</param>
        /// <param name="ngayBatDau"> ngày bắt đầu của thời giá nơi danhsachCP đưa vào</param>
        /// <param name="minSimilar">tỉ lệ đồng dạng tối thiểu</param>
        /// <param name="soNgay">số ngày thời giá thay đổi sau khi so khớp</param>
        public void Testing_TimKiemSuGiongNhauQuaKhu_ToanBoCP(DanhSachCoPhieu danhSachCP, string ngayBatDau, string ngayKetThuc, float minSimilar, int soNgay)
        {
            List<string> listContent = new List<string>();
            List<string> listNgayBatDau = new List<string>();
            List<string> listNgayKetThuc = new List<string>();
            List<string> listTenCP = new List<string>();

            List<float> listCosineSimilar = new List<float>();
            List<float> listCosineSimilarKhoiLuong = new List<float>();
            List<float> listGiaTongHop = new List<float>();
            List<float> listKhoiLuong = new List<float>();
            List<List<float>> listGiaThayDoi = new List<List<float>>();

            float thaydoiGia;
            string text;

            text = "Khoang thoi gian dua vao:: Ngay bat dau: " + ngayBatDau + " -- Ngay ket thuc: " + ngayKetThuc;
            listContent.Add(text);
            listContent.Add("Dong dang toi thieu: " + minSimilar + " -- Khoang cach ngay thay doi gia: " + soNgay + "\r\n");
            listContent.Add("CPGoc\t\tCPQuaKhu\tNgayBatDau\t\tNgayKetThuc\t\tCosineSimilar\t\tCosiKhoiLuong\t\tThayDoiGia");
            listContent.Add("-------------------------------------------------------------------------------------------------------------------------------------------------------");

            foreach (CoPhieu CP in danhSachCP.DanhSachCoPhieu_List)
            {
                listGiaTongHop = CP.Xuly_LayDanhSachGiaTongHop();
                if (CoreFunctions.Tk_GetAverage(listGiaTongHop) < 15)
                    continue;

                listKhoiLuong = CP.DanhSachKhoiLuongGiaoDich;
                Testing_TimKiemSuGiongNhauQuaKhu(listGiaTongHop, listKhoiLuong, 1, ngayBatDau, minSimilar, soNgay, out listGiaThayDoi
                    , out listNgayBatDau, out listNgayKetThuc, out listTenCP, out listCosineSimilar, out listCosineSimilarKhoiLuong);

                if (listGiaThayDoi.Count != 0)
                {
                    for (int i = 0; i < listGiaThayDoi.Count; i++)
                    {
                        if (listCosineSimilarKhoiLuong[i] < 0.3)
                            continue;

                        thaydoiGia = (float)Math.Round(Math.Log(listGiaThayDoi[i][0] / listGiaThayDoi[i][listGiaThayDoi[i].Count - 1]), 3);
                        if (listCosineSimilar[i].ToString().Length <= 5)
                            text = CP.TenCoPhieu + "\t\t";
                        else
                            text = CP.TenCoPhieu + "\t\t\t";

                        text += listTenCP[i] + "\t\t" + listNgayBatDau[i] + "\t\t" + listNgayKetThuc[i]
                            + "\t\t" + listCosineSimilar[i] + "\t\t\t" + listCosineSimilarKhoiLuong[i] + "\t\t\t" + thaydoiGia;

                        listContent.Add(text);
                    }
                    listContent.Add("");
                }
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_TimKiemSuGiongNhauQuaKhu_ToanBoCP.txt", listContent);
        }

        public void Testing_TimKiemSuGiongNhauQuaKhu_ToanBoCP_KiemtraTuongLai(DanhSachCoPhieu danhSachCP, DanhSachCoPhieu danhsachCPTuongLai, string ngayBatDau, string ngayKetThuc, float minSimilar, int soNgay)
        {
            List<string> listContent = new List<string>();
            List<string> listNgayBatDau = new List<string>();
            List<string> listNgayKetThuc = new List<string>();
            List<string> listTenCP = new List<string>();

            List<float> listCosineSimilar = new List<float>();
            List<float> listCosineSimilarKhoiLuong = new List<float>();
            List<float> listGiaTongHop = new List<float>();
            List<float> listKhoiLuong = new List<float>();
            List<float> listGiaTuongLai = new List<float>();
            List<float> listTemp = new List<float>();
            List<List<float>> listGiaThayDoi = new List<List<float>>();

            float thaydoiGia, thayDoiGiaTuongLai = 0f, cosine;
            string text;

            text = "Khoang thoi gian dua vao:: Ngay bat dau: " + ngayBatDau + " -- Ngay ket thuc: " + ngayKetThuc;
            listContent.Add(text);
            listContent.Add("Dong dang toi thieu: " + minSimilar + " -- Khoang cach ngay thay doi gia: " + soNgay + "\r\n");
            listContent.Add("CPGoc\t\tCPQuaKhu\tNgayBatDau\t\tNgayKetThuc\t\tCosineGia\t\tCosineKhLuong\t\tThayDoiGia\t\tThayDoiCPDangXet\t\tCosineGia");
            listContent.Add("-------------------------------------------------------------------------------------------------------------------------------------------------------");

            foreach (CoPhieu CP in danhSachCP.DanhSachCoPhieu_List)
            {
                listGiaTongHop = CP.Xuly_LayDanhSachGiaTongHop();
                if (CoreFunctions.Tk_GetAverage(listGiaTongHop) < 15)
                    continue;

                listKhoiLuong = CP.DanhSachKhoiLuongGiaoDich;
                Testing_TimKiemSuGiongNhauQuaKhu(listGiaTongHop, listKhoiLuong, 1, ngayBatDau, minSimilar, soNgay, out listGiaThayDoi
                    , out listNgayBatDau, out listNgayKetThuc, out listTenCP, out listCosineSimilar, out listCosineSimilarKhoiLuong);

                if (listGiaThayDoi.Count != 0)
                {
                    foreach (CoPhieu CPTuongLai in danhsachCPTuongLai.DanhSachCoPhieu_List)
                        if (CP.TenCoPhieu == CPTuongLai.TenCoPhieu)
                        {
                            listGiaTuongLai = CPTuongLai.Xuly_LayDanhSachGiaTongHop();
                            thayDoiGiaTuongLai = (float)Math.Round(Math.Log(listGiaTuongLai[0] / listGiaTuongLai[listGiaTuongLai.Count - 1]), 3);
                            break;
                        }

                    for (int i = 0; i < listGiaThayDoi.Count; i++)
                    {
                        if (listCosineSimilarKhoiLuong[i] < 0.3)
                            continue;

                        cosine = CoreFunctions.MR_TinhCosineSimilar(CoreFunctions.Tk_GetZScores(listGiaTuongLai)
                            , CoreFunctions.Tk_GetZScores(listGiaThayDoi[i]));

                        cosine = (float)Math.Round(cosine, 3);

                        thaydoiGia = (float)Math.Round(Math.Log(listGiaThayDoi[i][0] / listGiaThayDoi[i][listGiaThayDoi[i].Count - 1]), 3);
                        if (listCosineSimilar[i].ToString().Length <= 5)
                            text = CP.TenCoPhieu + "\t";
                        else
                            text = CP.TenCoPhieu + "\t";

                        text += listTenCP[i] + "\t" + listNgayBatDau[i] + "\t\t" + listNgayKetThuc[i]
                            + "\t\t" + listCosineSimilar[i] + "\t\t\t" + listCosineSimilarKhoiLuong[i] + "\t\t\t" + thaydoiGia;
                        text += "\t\t\t" + thayDoiGiaTuongLai + "\t\t\t" + cosine;

                        listContent.Add(text);
                    }
                    listContent.Add("");
                }
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_TimKiemSuGiongNhauQuaKhu_ToanBoCP_TuongLai.txt", listContent);
        }

        /// <summary>
        /// Testing load file Testing_TimKiemSuGiongNhauQuaKhu_ToanBoCP.txt
        /// Chuyển sang dạng Positive - Negative
        /// </summary>
        /// <param name="path">đường dẫn tới file</param>
        /// <param name="numberRowSkip">số dòng đầu bị bỏ qua</param>
        /// <param name="listTenCP">danh sách tên CP tìm được quá khứ ở file</param>
        /// <param name="listHeSo">các hệ số: average - min - max - % - % x Average - count - %Pos/Neg</param>
        public void Testing_TimKiemSuGiongNhauQuaKhu_LoadFile(string path, int numberRowSkip, out List<string> listTenCP, out List<List<float>> listHeSo)
        {
            List<List<string>> listContent = CoreFunctions.File_LoadAnyFile(path, numberRowSkip, new string[] { "\t" });

            List<float> listPostive = new List<float>();
            List<float> listNegative = new List<float>();
            List<string> listContentFile = new List<string>();

            listTenCP = new List<string>();
            listHeSo = new List<List<float>>();

            string nameCP = "", text;
            int total;
            float value, max, min, average, percentPositive, percentNegative, multiplyPositve, multiplyNegative, percentTotal, dolech;

            foreach (List<string> listStr in listContent)
            {
                if (nameCP == "" || listStr[0] != nameCP) /// chuyển sang mã CK mới
                {
                    if (listPostive.Count != 0 || listNegative.Count != 0)
                    {
                        total = listPostive.Count + listNegative.Count;

                        percentNegative = (float)Math.Round((float)listNegative.Count / total, 2);
                        percentPositive = (float)Math.Round((float)listPostive.Count / total, 2);

                        /// Tính cho Positive
                        CoreFunctions.Tk_ThongKeMoTa(listPostive, out max, out min, out average);
                        dolech = CoreFunctions.Tk_PopularStandardDeviation(listPostive);
                        multiplyPositve = (float)Math.Round(average * percentPositive, 3);
                        listHeSo.Add(new List<float>());
                        listHeSo[listHeSo.Count - 1].AddRange(new float[] { average, dolech, min, max, percentPositive, listPostive.Count, multiplyPositve });

                        /// Tính cho Negative
                        CoreFunctions.Tk_ThongKeMoTa(listNegative, out max, out min, out average);
                        dolech = CoreFunctions.Tk_PopularStandardDeviation(listNegative);
                        multiplyNegative = (float)Math.Round(average * percentNegative, 3);
                        listHeSo.Add(new List<float>());
                        listHeSo[listHeSo.Count - 1].AddRange(new float[] { average, dolech, min, max, percentNegative, listNegative.Count, multiplyNegative });

                        if (multiplyNegative != 0.0000f && multiplyPositve != 0.0000f)
                            percentTotal = (float)Math.Round(Math.Log(multiplyPositve / multiplyNegative * (-1)), 3);
                        else
                            percentTotal = 1f;

                        listHeSo[listHeSo.Count - 1].Add(percentTotal);
                        listHeSo[listHeSo.Count - 2].Add(percentTotal);
                    }

                    listPostive = new List<float>();
                    listNegative = new List<float>();

                    nameCP = listStr[0];

                    listTenCP.Add(nameCP); /// add cho positive
                    listTenCP.Add(nameCP); /// add cho negative
                }

                value = float.Parse(listStr[listStr.Count - 1]);
                if (value >= 0.00f)
                    listPostive.Add(value);
                else
                    listNegative.Add(value);
            }

            /// Còn phần chưa xử lý nên sẽ xử lý tiếp
            total = listPostive.Count + listNegative.Count;

            percentNegative = (float)Math.Round((float)listNegative.Count / total, 2);
            percentPositive = (float)Math.Round((float)listPostive.Count / total, 2);

            /// Tính cho Positive
            CoreFunctions.Tk_ThongKeMoTa(listPostive, out max, out min, out average);
            dolech = CoreFunctions.Tk_PopularStandardDeviation(listPostive);
            multiplyPositve = (float)Math.Round(average * percentPositive, 3);
            listHeSo.Add(new List<float>());
            listHeSo[listHeSo.Count - 1].AddRange(new float[] { average, dolech, min, max, percentPositive, listPostive.Count, multiplyPositve });

            /// Tính cho Negative
            CoreFunctions.Tk_ThongKeMoTa(listNegative, out max, out min, out average);
            dolech = CoreFunctions.Tk_PopularStandardDeviation(listNegative);
            multiplyNegative = (float)Math.Round(average * percentNegative, 3);
            listHeSo.Add(new List<float>());
            listHeSo[listHeSo.Count - 1].AddRange(new float[] { average, dolech, min, max, percentNegative, listNegative.Count, multiplyNegative });

            if (multiplyNegative != 0.0000f && multiplyPositve != 0.0000f)
                percentTotal = (float)Math.Round(Math.Log(multiplyPositve / multiplyNegative * (-1)), 3);
            else
                percentTotal = 1f;

            listHeSo[listHeSo.Count - 1].Add(percentTotal);
            listHeSo[listHeSo.Count - 2].Add(percentTotal);

            listContentFile.Add("CP\t\tType\t\tAverage\t\tStd\t\tMin\t\tMax\t\tPercent\t\tCount\t\t%xAvg\t\t%Pos/Neg");
            listContentFile.Add("---------------------------------------------------------------------------------------------------------------------------------------");
            for (int i = 0; i < listTenCP.Count; i++)
            {
                //text = listTenCP[i] + CoreFunctions.Xuly_ChuoiTraVe(listTenCP[i], 3, 2, 1, "\t");
                text = listTenCP[i] + "\t";
                if (i % 2 == 0)
                    text += "+\t\t";
                else
                    text += "-\t\t";

                foreach (float values in listHeSo[i])
                    //text += values.ToString() + CoreFunctions.Xuly_ChuoiTraVe(values.ToString(), 5, 2, 1, "\t");
                    text += values.ToString() + "\t\t";
                listContentFile.Add(text);
                if (i % 2 == 1)
                    listContentFile.Add("");
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_TimKiemSuGiongNhauQuaKhu_PosNeg.txt", listContentFile);
        }

        /// <summary>
        /// Dùng để kiểm tra tương lai (dùng với khoảng thời gian tương lai)
        /// Ghi File: Testing_TimKiemSuGiongNhauQuaKhu_KiemTraTuongLai.txt
        /// </summary>
        /// <param name="listTenCP">danh sách tên cổ phiếu</param>
        /// <param name="listHeSo">danh sách các hệ số</param>
        public void Testing_TimKiemSuGiongNhauQuaKhu_KiemTraTuongLai(List<string> listTenCP, List<List<float>> listHeSo)
        {
            List<string> listTenCPTesting = new List<string>();
            string text;
            int index;
            #region * Lọc CP từ các hệ số
            for (int i = 0; i < listTenCP.Count; i = i + 2)
                listTenCPTesting.Add(listTenCP[i]);
            #endregion

            #region * Test Tương Lai
            List<float> listGiaTongHop;
            List<string> listContent = new List<string>();
            listContent.Add("CP\t\tAverage\t\tStd\t\tMin\t\tMax\t\tPercent\t\tCount\t\t%xAvg\t\t%Pos/Neg\t\tTuongLai");
            listContent.Add("--------------------------------------------------------------------------------------------------------------------------------------------------------------------");
            float tanggia;
            foreach (CoPhieu CP in this._danhSachCoPhieu)
                if (listTenCPTesting.Contains(CP.TenCoPhieu) == true)
                {
                    index = listTenCP.IndexOf(CP.TenCoPhieu);

                    listGiaTongHop = CP.Xuly_LayDanhSachGiaTongHop();
                    tanggia = (float)Math.Round(Math.Log(listGiaTongHop[0] / listGiaTongHop[listGiaTongHop.Count - 1]), 3);

                    for (int i = 0; i < 2; i++)
                    {
                        text = CP.TenCoPhieu + CoreFunctions.Xuly_ChuoiTraVe(CP.TenCoPhieu, 3, 2, 1, "\t");

                        foreach (float value in listHeSo[index + i])
                            text += value + CoreFunctions.Xuly_ChuoiTraVe(CP.TenCoPhieu, 5, 2, 1, "\t");
                        text += "\t" + tanggia;
                        listContent.Add(text);
                    }
                    listContent.Add("");
                }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_TimKiemSuGiongNhauQuaKhu_KiemTraTuongLai.txt", listContent);
            #endregion
        }

        #endregion

        #region * Testing Tính Xu hướng
        /// <summary>
        /// Testing tính xu hướng, áp dụng thử cho tương lai
        /// Xuất file: Testing_XuHuong_KiemTraTuongLai.txt
        /// </summary>
        /// <param name="listXuHuongCP"></param>
        public void Testing_XuHuong_KiemTraTuongLai(List<List<float>> listXuHuongCP, List<string> listTenCP)
        {
            List<float> listGiaTongHop = new List<float>();
            List<string> listContentFile = new List<string>();

            float avgTotal, avgPositive, avgNegative, thaydoiGia;
            string text = "CP\t\t\tAvgTotal\t\tAvgPos\t\tAvgNeg\t\tCountPos\t\tCountNeg\t\t%ThayDoiGia";
            int index, countPositive, countNegative;

            listContentFile.Add(text);
            listContentFile.Add("------------------------------------------------------------------------------------------------------------------------");

            for (int i = 0; i < listXuHuongCP.Count; i++)
            {
                index = this.KiemTra_DanhSachCoPhieuChuaCoPhieu(listTenCP[i]);
                if (index == -1)
                    continue;

                listGiaTongHop = _danhSachCoPhieu[index].Xuly_LayDanhSachGiaTongHop();

                thaydoiGia = (float)Math.Round(Math.Log(listGiaTongHop[0] / listGiaTongHop[listGiaTongHop.Count - 1]), 3);

                CoreFunctions.TK_ThongKeAverage(listXuHuongCP[i], out avgTotal, out avgPositive, out avgNegative,
                    out countPositive, out countNegative, 4);

                //if (!(countPositive < countNegative && countNegative - countPositive < 6
                //    && avgPositive < Math.Abs(avgNegative) && avgPositive > 0.02f))
                //    continue;

                text = listTenCP[i];

                if (text.Length > 5)
                    text += "\t\t";
                else
                    text += "\t\t\t";

                if (avgTotal.ToString().Length > 5)
                    text += avgTotal + "\t\t";
                else
                    text += avgTotal + "\t\t\t";

                if (avgPositive.ToString().Length > 5)
                    text += avgPositive + "\t\t";
                else
                    text += avgPositive + "\t\t\t";

                if (avgNegative.ToString().Length > 5)
                    text += avgNegative + "\t\t";
                else
                    text += avgNegative + "\t\t\t";

                text += countPositive + "\t\t\t";
                text += countNegative + "\t\t\t";
                text += thaydoiGia;

                listContentFile.Add(text);
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_XuHuong_KiemTraTuongLai.txt", listContentFile);
        }
        #endregion

        #region * Testing Tính Volatility (độ bay hơi)
        /// <summary>
        /// Tính Volatility (độ bay hơi) liên quan đến rủi ro
        /// Chỉ tính trên giá.        
        /// </summary>
        public void Testing_TinhVolatility(ref List<float> listResult, ref List<float> listBetaVol)
        {
            listResult = new List<float>();
            listBetaVol = new List<float>();
            List<float> listStd = new List<float>();

            float sum = 0f, tb = 0f, betaVol;
            int count = 0;

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                ///List<float> listThayDoiGia = CP.DanhSachThayDoiGiaTongHopTungNgay;
                List<float> listThayDoiGia = CoreFunctions.Tk_GetDailyReturn(CP.DanhSachGiaDongCua);
                listStd.Add((float)Math.Round(CoreFunctions.Tk_PopularStandardDeviation(listThayDoiGia), 3));
                listResult.Add(
                    (float)Math.Round(CoreFunctions.MR_TinhVolatility_ContinuousMethod(listThayDoiGia, 1f / listThayDoiGia.Count), 3));
            }

            for (int i = 0; i < listResult.Count; i++)
                if (listResult[i].ToString() != "NaN")
                {
                    sum += listResult[i];
                    count++;
                }
            tb = (float)Math.Round(sum / count, 3);

            List<string> listContent = new List<string>();
            listContent.Add(HeaderFile);
            listContent.Add("Volatility trung binh: " + tb.ToString());
            listContent.Add("TenCP\t\tVolatility\tStd\tBetaVol");
            listContent.Add("---------------------------------------------");
            for (int i = 0; i < listResult.Count; i++)
            {
                betaVol = 0;
                if (listResult[i].ToString() != "NaN")
                {
                    betaVol = (float)Math.Round(listResult[i] / tb, 2);
                    listBetaVol.Add(betaVol);
                }
                else
                {
                    listBetaVol.Add(0);
                    listResult[i] = 0f;
                }
                listContent.Add(this._danhSachCoPhieu[i].TenCoPhieu 
                    + "\t\t" + listResult[i] 
                    + "\t\t" + listStd[i]
                    + "\t\t\t" + betaVol.ToString());
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_TinhVolatility.txt", listContent);

        }

        /// <summary>
        /// Tính Volatility (độ bay hơi) liên quan đến rủi ro
        /// Chỉ tính trên giá - khối lượng
        /// Ghi file: Testing_TinhVolatility_GiaKhoiLuong.txt
        /// </summary>
        public void Testing_TinhVolatilityGia_KhoiLuong()
        {          

            List<float> listResultGia = new List<float>();
            List<float> listAvgGia = new List<float>();
            List<float> listChechLechGiaVNINDEX = new List<float>();

            float volGia;
            float avg_volGia = 0f;
            int count = 0;

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                volGia = CoreFunctions.MR_TinhVolatility_ContinuousMethod(CP.DanhSachThayDoiGiaTongHopTungNgay, 1f / (CP.SoNgayGiaoDich - 1));
                listResultGia.Add(volGia);
                listAvgGia.Add(CoreFunctions.Tk_GetAverage(CP.DanhSachThayDoiGiaTongHopTungNgay));
            }

          
            foreach (float volatilityGia in listResultGia)
                if (volatilityGia.ToString() != "NaN")
                {
                    count++;
                    avg_volGia += volatilityGia;
                }
            avg_volGia = (float)Math.Round(avg_volGia / count, 3);

            List<string> listContent = new List<string>();
            listContent.Add("Tinh Volatility cua gia va khoi luong giao dich cua CP");
            listContent.Add("Ngay bat dau: " + this._ngayBatDau + " -- Ngay ket thuc: " + this._ngayKetThuc);
            listContent.Add("Sau khi tinh volatility cho VNIndex va cac CP thi so sanh voi nhau o cot: C.lechGia va C.lechKhoiluong");
            ///listContent.Add("**Volatility Gia VNIndex: " + vnindex_volatility_gia);
            listContent.Add("**Average Volatility Gia: " + avg_volGia);
            listContent.Add("");
            listContent.Add("TenCP\t\tVolGia\t\tC.lechGia\tC.lechAvgGia");
            listContent.Add("---------------------------------------------------");

            float chechlechGia;

            for (int i = 0; i < listResultGia.Count; i++)
            {
                chechlechGia = (float)Math.Round(Math.Log(listResultGia[i] / avg_volGia), 3);
                listContent.Add(this._danhSachCoPhieu[i].TenCoPhieu + "\t\t" + listResultGia[i] + "\t\t" + listChechLechGiaVNINDEX[i]
                     + "\t\t" + chechlechGia);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_TinhVolatility_GiaKhoiLuong.txt", listContent);
        }

        #endregion

        #region Kiểm tra tín hiệu       

        public void Testing_MACD_Statistic_TinHieuMua(int chukyMACD, int KhoangCachBreak, int soNgayBanCP
            , int khoangcachToiThieu2dinhHistogram = 5, bool flag_GiaDieuChinh = false, string nameCPTest = "")
        {
            #region Biến
            bool flag_Duong = false;
            int count = 0;
            List<string> listContent = new List<string>();
            List<float> MACD = new List<float>();
            List<float> signalLine = new List<float>();
            List<float> histogram = new List<float>();
            List<float> listSignalBuySell;
            List<float> priceOfStock = new List<float>();

            List<int> listIDNgay = new List<int>();
            List<int> temp = new List<int>();            
            List<int> soTinHieu_Duong = new List<int>(); /// tín hiệu bán
            List<int> soTinHieu_Am = new List<int>(); /// tín hiệu mua
                                                     
            List<float> listReward = new List<float>();
            List<float> listReward_Duong = new List<float>();
            List<float> listReward_Am = new List<float>();
            List<float> listTemp_float = new List<float>();
            int id_mua, id_ban, min;
            float temp_float;
            bool flag_DangGiuCP = false;

            List<int> listNgayNamGiu = new List<int>();
            #endregion

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                if (nameCPTest != "" && CP.TenCoPhieu != nameCPTest)
                    continue;

                if (flag_GiaDieuChinh == true)
                    priceOfStock = CP.DanhSachGiaDongCua_DieuChinh;
                else
                    priceOfStock = CP.DanhSachGiaDongCua;

                #region *** Tính MACD_smoothDEMA, histogram
                MACD = new List<float>();
                signalLine = new List<float>();
                Indicators.MACD_smoothDEMA(priceOfStock, 12, 26, chukyMACD, ref MACD, ref signalLine);
                histogram = new List<float>();

                for (int j = 0; j < signalLine.Count; j++)
                    histogram.Add(MACD[j] - signalLine[j]);
                listSignalBuySell = Indicators.GetSignalBuySell(histogram, khoangcachToiThieu2dinhHistogram);
                #endregion

                #region *** Statistic theo Historgram
                temp = new List<int>();

                if (listSignalBuySell[0] > 0)
                    flag_Duong = false;
                else
                    flag_Duong = true;

                for (int i = 0; i < listSignalBuySell.Count; i++)
                {
                    if (listSignalBuySell[i] > 0 && !flag_Duong)
                    {
                        flag_Duong = true;
                        temp = soTinHieu_Duong;
                        count = 0;
                        for (int j = i; j < listSignalBuySell.Count; j++)
                            if (listSignalBuySell[j] > 0)
                                count++;
                            else if (listSignalBuySell[j] < 0)
                            {
                                i = j;
                                break;
                            }
                        temp.Add(count);
                    }
                    else if (listSignalBuySell[i] < 0 && flag_Duong)
                    {
                        flag_Duong = false;
                        temp = soTinHieu_Am;
                        count = 0;
                        for (int j = i; j < listSignalBuySell.Count; j++)
                            if (listSignalBuySell[j] < 0)
                                count++;
                            else if (listSignalBuySell[j] > 0)
                            {
                                i = j;
                                break;
                            }
                        temp.Add(count);
                    }
                }
                #endregion

                #region  Tính theo giá trị đạt được khi tính toán theo tín hiệu histogram

                #region Mua CP khi histogram đang ở dưới 0 [có 3 đỉnh] bán khi có tín hiệu histogram dương đầu tiên
                flag_DangGiuCP = false;
                listTemp_float = new List<float>();
                listTemp_float = priceOfStock;
                id_mua = 0;
                min = Math.Min(500, listSignalBuySell.Count - 1);
                for (int i = min; i >= 0; i--)
                {
                    if (flag_DangGiuCP == false && listSignalBuySell[i] > 0)
                    {
                        count = 1;
                        for (int j = i - 1; j >= 0; j--)
                            if (listSignalBuySell[j] < 0)
                            {
                                i = j + 1;
                                break;
                            }
                            else if (listSignalBuySell[j] > 0)
                            {
                                count++;
                                if (count > 2)
                                {
                                    flag_DangGiuCP = true;
                                    i = j - 1;
                                    id_mua = j;
                                    break;
                                }
                            }
                            else if (flag_DangGiuCP == true)
                            {
                                temp_float = (listTemp_float[j] - listTemp_float[id_mua]) / listTemp_float[id_mua];
                                if (temp_float < -0.02f)
                                {
                                    flag_DangGiuCP = false;
                                    listReward.Add(temp_float);
                                    listReward_Am.Add(temp_float);
                                }
                            }

                    }
                    else if (flag_DangGiuCP == true && listSignalBuySell[i] < 0)
                    {
                        flag_DangGiuCP = false;
                        id_ban = i;
                        temp_float = (listTemp_float[id_ban] - listTemp_float[id_mua]) / listTemp_float[id_mua];

                        listNgayNamGiu.Add(id_mua - id_ban);

                        listReward.Add(temp_float);

                        if (temp_float > 0f)
                            listReward_Duong.Add(temp_float);
                        else
                            listReward_Am.Add(temp_float);
                    }
                }
                #endregion

                #region Mua CP khi histogram đang ở trên 0 [có 1 đỉnh] bán khi có tín hiệu histogram dương thứ 2
                //flag_DangGiuCP = false;
               
                //listTemp_float = priceOfStock;
                //id_mua = 0;
                //min = Math.Min(500, listSignalBuySell.Count - 1);
               
                //for (int i = min; i >= 0; i--)                
                //    if (flag_DangGiuCP == false && listSignalBuySell[i] < 0)
                //    {
                //        count = 1;
                //        int count_giam = 0;
                //        for (int j = i; j > 0; j--)
                //        {
                //            if (histogram[j] > histogram[j - 1] && histogram[j - 1] > 0)
                //                count_giam++;
                //            else if (histogram[j] < 0)
                //            {
                //                count_giam = 0;
                //                i = j - 1;
                //                if (flag_DangGiuCP == true)
                //                {
                //                    flag_DangGiuCP = false;
                //                    id_ban = j - 1;
                //                    listNgayNamGiu.Add(id_mua - id_ban);
                //                    temp_float = (listTemp_float[id_ban] - listTemp_float[id_mua]) / listTemp_float[id_mua];
                //                    listReward.Add(temp_float);
                //                    if (temp_float > 0)
                //                        listReward_Duong.Add(temp_float);
                //                    else
                //                        listReward_Am.Add(temp_float);
                //                }
                //                break;
                //            }
                //            else if (flag_DangGiuCP == false
                //                && count_giam >= 5 && histogram[j] < histogram[j - 1])
                //            {
                //                flag_DangGiuCP = true;
                //                id_mua = j - 1;
                //                count_giam = 0;
                //            }
                //            else if (flag_DangGiuCP == true && listSignalBuySell[j] < 0)
                //            {
                //                flag_DangGiuCP = false;
                //                count++;
                //                id_ban = j - 1;
                //                listNgayNamGiu.Add(id_mua - id_ban);
                //                temp_float = (listTemp_float[id_ban] - listTemp_float[id_mua]) / listTemp_float[id_mua];
                //                listReward.Add(temp_float);
                //                if (temp_float > 0)
                //                    listReward_Duong.Add(temp_float);
                //                else
                //                    listReward_Am.Add(temp_float);

                //                i = j - 1;
                //                break;
                //            }
                //        }
                //    }                   
                
                #endregion
                #endregion
            }

            #region Tính toán thống kê và ghi file
            List<List<float>> listStatistic_Dinh = new List<List<float>>();
            List<List<int>> listCountTinHieu = new List<List<int>>();
            listCountTinHieu.Add(soTinHieu_Duong);
            listCountTinHieu.Add(soTinHieu_Am);

            foreach (List<int> listValues in listCountTinHieu)
            {
                listStatistic_Dinh.Add(new List<float>());
                count = 0;
                for (int i = 1; i <= 4; i++)
                {
                    for (int j = 0; j < listValues.Count; j++)
                        if (listValues[j] == i)
                            count++;
                    listStatistic_Dinh[listStatistic_Dinh.Count - 1]
                        .Add((float)Math.Round((float)count / listValues.Count, 2));
                }
            }

            float avg_Duong, avg_Am, std_Duong, std_Am;
            avg_Duong = CoreFunctions.Tk_GetAverage(soTinHieu_Duong);
            avg_Duong = (float)Math.Round(avg_Duong, 2);
            avg_Am = CoreFunctions.Tk_GetAverage(soTinHieu_Am);
            avg_Am = (float)Math.Round(avg_Am, 2);
            std_Duong = CoreFunctions.Tk_PopularStandardDeviation(soTinHieu_Duong);
            std_Duong = (float)Math.Round(std_Duong, 2);
            std_Am = CoreFunctions.Tk_PopularStandardDeviation(soTinHieu_Am);
            std_Am = (float)Math.Round(std_Am, 2);

            float avg_Reward = CoreFunctions.Tk_GetAverage(listReward);
            avg_Reward = (float)Math.Round(avg_Reward, 2);
            float std_Reward = CoreFunctions.Tk_PopularStandardDeviation(listReward);
            std_Reward = (float)Math.Round(std_Reward, 2);
            

            listContent = new List<string>();

            if (nameCPTest != "")
                listContent.Add("[" + nameCPTest + "]");
            else
                listContent.Add("[All]");

            listContent.Add("Loai\t\tCOUNT\t\tAVG\t\tSTD\t\t1D\t\t2D\t\t3D\t\t4D");

            listContent.Add("Duong\t\t" + soTinHieu_Duong.Count + "\t\t" + avg_Duong + "\t\t" + std_Duong
                + "\t\t" + listStatistic_Dinh[0][0] + "\t\t" + listStatistic_Dinh[0][1] + "\t\t" + listStatistic_Dinh[0][2]
                + "\t\t" + listStatistic_Dinh[0][3]);
            listContent.Add("Am\t\t" + soTinHieu_Am.Count + "\t\t" + avg_Am + "\t\t" + std_Am
                + "\t\t" + listStatistic_Dinh[1][0] + "\t\t" + listStatistic_Dinh[1][1] + "\t\t" + listStatistic_Dinh[1][2]
                + "\t\t" + listStatistic_Dinh[1][3]);

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Reward]");
            listContent.Add("Reward\t\tCOUNTB&S\tAVG\t\tSTD");
            listContent.Add("Reward\t\t" + listReward.Count + "\t\t" + avg_Reward + "\t\t" + std_Reward);

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Reward Duong/Am]");
            listContent.Add("Reward\t\tCOUNTB&S\tAVG\t\tSTD");
            avg_Duong = CoreFunctions.Tk_GetAverage(listReward_Duong);
            avg_Duong = (float)Math.Round(avg_Duong, 2);
            std_Duong = CoreFunctions.Tk_PopularStandardDeviation(listReward_Duong);
            std_Duong = (float)Math.Round(std_Duong, 2);
            listContent.Add("Duong\t\t\t" + listReward_Duong.Count + "\t\t" + avg_Duong + "\t\t" + std_Duong);

            avg_Am = CoreFunctions.Tk_GetAverage(listReward_Am);
            avg_Am = (float)Math.Round(avg_Am, 2);
            std_Am = CoreFunctions.Tk_PopularStandardDeviation(listReward_Am);
            std_Am = (float)Math.Round(std_Am, 2);
            listContent.Add("Am\t\t\t" + listReward_Am.Count + "\t\t" + avg_Am + "\t\t" + std_Am);

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Ngay Nam Giu CP]");
            listContent.Add("COUNT\t\tAVG\t\tSTD");
            avg_Duong = CoreFunctions.Tk_GetAverage(listNgayNamGiu);
            avg_Duong = (float)Math.Round(avg_Duong, 2);
            std_Duong = CoreFunctions.Tk_PopularStandardDeviation(listNgayNamGiu);
            std_Duong = (float)Math.Round(std_Duong, 2);
            listContent.Add(listNgayNamGiu.Count + "\t\t" + avg_Duong + "\t\t" + std_Duong);

            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\Data\Testing_Statistic_TinHieu.txt", listContent);
            #endregion
        }

        public void Testing_AvgRSIMFIIMI_Statistic_TinHieuMua(int chukyMACD, int KhoangCachBreak, int soNgayBanCP
            , ref List<int> soNgayCachDinhGanNhat, ref List<int> soDinhHistogram, int khoangcachToiThieu2dinhHistogram = 5)
        {
            #region Biến
            bool flag_Duong = false;
            bool flag = false;
            int count = 0;
            List<string> listContent = new List<string>();
            List<float> MACD = new List<float>();
            List<float> signalLine = new List<float>();
            List<float> histogram = new List<float>();
            List<float> listSignalBuySell;
            List<float> priceOfStock = new List<float>();
            List<float> listValueDuong = new List<float>();
            List<float> listValueAm = new List<float>();

            List<int> listIDNgay = new List<int>();
            List<int> temp = new List<int>();
            List<int> soTinHieu_Duong = new List<int>(); /// tín hiệu bán
            List<int> soTinHieu_Am = new List<int>(); /// tín hiệu mua
            soNgayCachDinhGanNhat = new List<int>();                                                    
                                                      
            List<float> RSI = new List<float>();
            List<float> MFI = new List<float>();
            List<float> IMI = new List<float>();
            List<float> listTongHopIMI_RSI_MFI = new List<float>();
            soDinhHistogram = new List<int>();
            #endregion
            
            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                #region Tính RSI, MFI, IMI
                RSI = new List<float>(); IMI = new List<float>(); MFI = new List<float>();

                RSI = Indicators.RSI(20, CP.DanhSachGiaDongCua);
                IMI = Indicators.IMI(14, CP.DanhSachGiaMoCua, CP.DanhSachGiaDongCua);
                MFI = Indicators.MFI(14, CP.DanhSachGiaCaoNhat, CP.DanhSachGiaThapNhat,
                            CP.DanhSachGiaDongCua, CP.DanhSachKhoiLuongGiaoDich_Int);
                listTongHopIMI_RSI_MFI = new List<float>();
                for (int i = 0; i < IMI.Count && i < RSI.Count && i < MFI.Count; i++)
                    listTongHopIMI_RSI_MFI.Add((IMI[i] + RSI[i] + MFI[i]) / 3);
                listTongHopIMI_RSI_MFI = Indicators.SMA(listTongHopIMI_RSI_MFI, 3);

                flag = false;
                #endregion

                #region Tính MACD_smoothDEMA
                MACD = new List<float>();
                signalLine = new List<float>();
                histogram = new List<float>();
                temp = new List<int>();
                Indicators.MACD_smoothDEMA(listTongHopIMI_RSI_MFI, 12, 26, chukyMACD, ref MACD, ref signalLine);

                #endregion

                #region Tính histogram và tín hiệu mua bán
                for (int j = 0; j < signalLine.Count; j++)
                    histogram.Add(MACD[j] - signalLine[j]);

                listSignalBuySell = Indicators.GetSignalBuySell(histogram, khoangcachToiThieu2dinhHistogram);
                #endregion

                #region Tính số ngày cách đỉnh gần nhất - theo tín hiệu của Histogram
                int soNgay = 9999;
                for (int i = 0; i < listSignalBuySell.Count; i++)
                    if (listSignalBuySell[i] != 0)
                    {
                        if (listSignalBuySell[i] > 0)
                        {
                            flag_Duong = false;
                            soNgay = i;
                        }
                        else if (listSignalBuySell[i] < 0)
                        {
                            flag_Duong = true;
                            //soNgay = i * -1;
                            soNgay = 9999;
                        }
                        break;
                    }
                soNgayCachDinhGanNhat.Add(soNgay);
                #endregion

                #region Tính số đỉnh trong 1 trend (tăng/giảm) theo histogram
                for (int i = 0; i < listSignalBuySell.Count; i++)
                {
                    if (listSignalBuySell[i] > 0 && !flag_Duong)
                    {
                        flag_Duong = true;
                        temp = soTinHieu_Duong;
                        count = 0;

                        for (int j = i; j < listSignalBuySell.Count; j++)
                            if (listSignalBuySell[j] > 0)
                            {
                                count++;
                                listValueDuong.Add(listTongHopIMI_RSI_MFI[j]);
                            }
                            else if (listSignalBuySell[j] < 0)
                            {
                                i = j;
                                break;
                            }
                        temp.Add(count);
                        if (count != 0 && flag == false)
                        {
                            flag = true;
                            soDinhHistogram.Add(count);
                        }
                    }
                    else if (listSignalBuySell[i] < 0 && flag_Duong)
                    {
                        flag_Duong = false;
                        temp = soTinHieu_Am;
                        count = 0;

                        for (int j = i; j < listSignalBuySell.Count; j++)
                            if (listSignalBuySell[j] < 0)
                            {
                                count++;
                                listValueAm.Add(listTongHopIMI_RSI_MFI[j]);
                            }
                            else if (listSignalBuySell[j] > 0)
                            {
                                i = j;
                                break;
                            }
                        temp.Add(count);
                        if (count != 0 && flag == false)
                        {
                            flag = true;
                            soDinhHistogram.Add(count);
                        }
                    }
                }
                #endregion
            }

            List<List<float>> listStatistic_Dinh = new List<List<float>>();
            List<List<int>> listCountTinHieu = new List<List<int>>();
            listCountTinHieu.Add(soTinHieu_Duong);
            listCountTinHieu.Add(soTinHieu_Am);

            foreach (List<int> listValues in listCountTinHieu)
            {
                listStatistic_Dinh.Add(new List<float>());
                count = 0;
                for (int i = 1; i <= 4; i++)
                {
                    for (int j = 0; j < listValues.Count; j++)
                        if (listValues[j] == i)
                            count++;
                    listStatistic_Dinh[listStatistic_Dinh.Count - 1]
                        .Add((float)Math.Round((float)count / listValues.Count, 2));
                }
            }

            float avg_Duong, avg_Am, std_Duong, std_Am , avg_valDuong, avg_valAm, std_ValDuong, std_ValAm;
            avg_Duong = CoreFunctions.Tk_GetAverage(soTinHieu_Duong);
            avg_Duong = (float)Math.Round(avg_Duong, 2);
            avg_Am = CoreFunctions.Tk_GetAverage(soTinHieu_Am);
            avg_Am = (float)Math.Round(avg_Am, 2);
            std_Duong = CoreFunctions.Tk_PopularStandardDeviation(soTinHieu_Duong);
            std_Duong = (float)Math.Round(std_Duong, 2);
            std_Am = CoreFunctions.Tk_PopularStandardDeviation(soTinHieu_Am);
            std_Am = (float)Math.Round(std_Am, 2);

            avg_valDuong = CoreFunctions.Tk_GetAverage(listValueDuong);
            avg_valDuong = (float)Math.Round(avg_valDuong, 2);
            avg_valAm = CoreFunctions.Tk_GetAverage(listValueAm);
            avg_valAm = (float)Math.Round(avg_valAm, 2);
            std_ValDuong = CoreFunctions.Tk_PopularStandardDeviation(listValueDuong);
            std_ValDuong = (float)Math.Round(std_ValDuong, 2);
            std_ValAm = CoreFunctions.Tk_PopularStandardDeviation(listValueAm);
            std_ValAm = (float)Math.Round(std_ValAm, 2);

            listContent = new List<string>();
            listContent.Add("[So Dinh/Break Dao Chieu]");
            listContent.Add("Loai\t\tCOUNT\t\tAVG\t\tSTD\t\t1D\t\t2D\t\t3D\t\t4D");

            listContent.Add("Duong\t\t" + soTinHieu_Duong.Count + "\t\t" + avg_Duong + "\t\t" + std_Duong
                + "\t\t" + listStatistic_Dinh[0][0] + "\t\t" + listStatistic_Dinh[0][1] + "\t\t" + listStatistic_Dinh[0][2]
                + "\t\t" + listStatistic_Dinh[0][3]);
            listContent.Add("Am\t\t" + soTinHieu_Am.Count + "\t\t" + avg_Am + "\t\t" + std_Am
                + "\t\t" + listStatistic_Dinh[1][0] + "\t\t" + listStatistic_Dinh[1][1] + "\t\t" + listStatistic_Dinh[1][2]
                + "\t\t" + listStatistic_Dinh[1][3]);

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Value]");
            listContent.Add("Loai\t\tAVG\t\tSTD");
            listContent.Add("Duong\t\t" + avg_valDuong + "\t\t" + std_ValDuong);
            listContent.Add("Am\t\t" + avg_valAm + "\t\t" + std_ValAm);
            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\Data\Testing_AVGRSIMFIIMI_Statistic_TinHieu.txt", listContent);
        }

        public void Testing_AvgRSIMFIIMI_Statistic_Reward(int chukyMACD, int KhoangCachBreak, int soNgayBanCP
         , ref List<int> soNgayCachDinhGanNhat, ref List<int> soDinhHistogram, int khoangcachToiThieu2dinhHistogram = 5)
        {
            #region Biến
            bool flag_Duong = false;
            bool flag = false;
            int count = 0;
            List<string> listContent = new List<string>();
            List<float> MACD = new List<float>();
            List<float> signalLine = new List<float>();
            List<float> histogram = new List<float>();
            List<float> listSignalBuySell;
            List<float> priceOfStock = new List<float>();
            List<float> listValueDuong = new List<float>();
            List<float> listValueAm = new List<float>();

            List<int> listIDNgay = new List<int>();
            List<int> temp = new List<int>();
            List<int> soTinHieu_Duong = new List<int>(); /// tín hiệu bán
            List<int> soTinHieu_Am = new List<int>(); /// tín hiệu mua
            soNgayCachDinhGanNhat = new List<int>();

            List<float> RSI = new List<float>();
            List<float> MFI = new List<float>();
            List<float> IMI = new List<float>();
            List<float> listTongHopIMI_RSI_MFI = new List<float>();
            soDinhHistogram = new List<int>();

            List<float> listReward = new List<float>();
            List<float> listReward_Duong = new List<float>();
            List<float> listReward_Am = new List<float>();
            int id_mua, id_ban;
            bool flag_DangGiuCP = false;
            float temp_float;
            #endregion

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                //if (CP.TenCoPhieu != "^VNINDEX")
                //    continue;
                
                #region Tính RSI, MFI, IMI
                RSI = new List<float>(); IMI = new List<float>(); MFI = new List<float>();

                RSI = Indicators.RSI(20, CP.DanhSachGiaDongCua);
                IMI = Indicators.IMI(14, CP.DanhSachGiaMoCua, CP.DanhSachGiaDongCua);
                MFI = Indicators.MFI(14, CP.DanhSachGiaCaoNhat, CP.DanhSachGiaThapNhat,
                            CP.DanhSachGiaDongCua, CP.DanhSachKhoiLuongGiaoDich_Int);
                listTongHopIMI_RSI_MFI = new List<float>();
                for (int i = 0; i < IMI.Count && i < RSI.Count && i < MFI.Count; i++)
                    listTongHopIMI_RSI_MFI.Add((IMI[i] + RSI[i] + MFI[i]) / 3);
                listTongHopIMI_RSI_MFI = Indicators.SMA(listTongHopIMI_RSI_MFI, 3);

                flag = false;
                #endregion

                #region Tính MACD_smoothDEMA
                MACD = new List<float>();
                signalLine = new List<float>();
                histogram = new List<float>();
                temp = new List<int>();
                Indicators.MACD_smoothDEMA(listTongHopIMI_RSI_MFI, 12, 26, chukyMACD, ref MACD, ref signalLine);

                #endregion

                #region Tính histogram và tín hiệu mua bán
                for (int j = 0; j < signalLine.Count; j++)
                    histogram.Add(MACD[j] - signalLine[j]);

                listSignalBuySell = Indicators.GetSignalBuySell(histogram, khoangcachToiThieu2dinhHistogram);
                #endregion

                #region Tính số ngày cách đỉnh gần nhất - theo tín hiệu của Histogram
                int soNgay = 9999;
                for (int i = 0; i < listSignalBuySell.Count; i++)
                    if (listSignalBuySell[i] != 0)
                    {
                        if (listSignalBuySell[i] > 0)
                        {
                            flag_Duong = false;
                            soNgay = i;
                        }
                        else if (listSignalBuySell[i] < 0)
                        {
                            flag_Duong = true;
                            //soNgay = i * -1;
                            soNgay = 9999;
                        }
                        break;
                    }
                soNgayCachDinhGanNhat.Add(soNgay);
                #endregion

                #region Tính số đỉnh trong 1 trend (tăng/giảm) theo histogram
                for (int i = 0; i < listSignalBuySell.Count; i++)
                {
                    if (listSignalBuySell[i] > 0 && !flag_Duong)
                    {
                        flag_Duong = true;
                        temp = soTinHieu_Duong;
                        count = 0;

                        for (int j = i; j < listSignalBuySell.Count; j++)
                            if (listSignalBuySell[j] > 0)
                            {
                                count++;
                                listValueDuong.Add(listTongHopIMI_RSI_MFI[j]);
                            }
                            else if (listSignalBuySell[j] < 0)
                            {
                                i = j;
                                break;
                            }
                        temp.Add(count);
                        if (count != 0 && flag == false)
                        {
                            flag = true;
                            soDinhHistogram.Add(count);
                        }
                    }
                    else if (listSignalBuySell[i] < 0 && flag_Duong)
                    {
                        flag_Duong = false;
                        temp = soTinHieu_Am;
                        count = 0;

                        for (int j = i; j < listSignalBuySell.Count; j++)
                            if (listSignalBuySell[j] < 0)
                            {
                                count++;
                                listValueAm.Add(listTongHopIMI_RSI_MFI[j]);
                            }
                            else if (listSignalBuySell[j] > 0)
                            {
                                i = j;
                                break;
                            }
                        temp.Add(count);
                        if (count != 0 && flag == false)
                        {
                            flag = true;
                            soDinhHistogram.Add(count);
                        }
                    }
                }
                #endregion

                #region  Tính theo giá trị đạt được khi tính toán theo tín hiệu histogram
                flag_DangGiuCP = false;
                List<float> listTemp_float = new List<float>();
                listTemp_float = CP.DanhSachGiaDongCua_DieuChinh;
                id_mua = 0;
                int min = Math.Min(500, listSignalBuySell.Count - 1);
                for (int i = min; i >= 0; i--)
                {
                    if (flag_DangGiuCP == false && listSignalBuySell[i] > 0)
                    {
                        count = 1;
                        for (int j = i - 1; j >= 0; j--)
                            if (listSignalBuySell[j] < 0)
                            {
                                i = j + 1;
                                break;
                            }
                            else if (listSignalBuySell[j] > 0)
                            {
                                count++;
                                if (count > 2)
                                {
                                    flag_DangGiuCP = true;
                                    i = j - 1;
                                    id_mua = j;
                                    break;
                                }
                            }
                    }
                    else if (flag_DangGiuCP == true && listSignalBuySell[i] < 0)
                    {
                        flag_DangGiuCP = false;
                        id_ban = i;
                        temp_float = (listTemp_float[id_ban] - listTemp_float[id_mua]) / listTemp_float[id_mua];
                        listReward.Add(temp_float);

                        if (temp_float > 0f)
                            listReward_Duong.Add(temp_float);
                        else
                            listReward_Am.Add(temp_float);
                    }
                }
                #endregion
            }

            #region Tính toán thống kê và ghi File
            List<List<float>> listStatistic_Dinh = new List<List<float>>();
            List<List<int>> listCountTinHieu = new List<List<int>>();
            listCountTinHieu.Add(soTinHieu_Duong);
            listCountTinHieu.Add(soTinHieu_Am);

            foreach (List<int> listValues in listCountTinHieu)
            {
                listStatistic_Dinh.Add(new List<float>());
                count = 0;
                for (int i = 1; i <= 4; i++)
                {
                    for (int j = 0; j < listValues.Count; j++)
                        if (listValues[j] == i)
                            count++;
                    listStatistic_Dinh[listStatistic_Dinh.Count - 1]
                        .Add((float)Math.Round((float)count / listValues.Count, 2));
                }
            }

            float avg_Duong, avg_Am, std_Duong, std_Am
                , avg_valDuong, avg_valAm, std_ValDuong, std_ValAm
                , avg_Reward, std_Reward;
            avg_Duong = CoreFunctions.Tk_GetAverage(soTinHieu_Duong);
            avg_Duong = (float)Math.Round(avg_Duong, 2);
            avg_Am = CoreFunctions.Tk_GetAverage(soTinHieu_Am);
            avg_Am = (float)Math.Round(avg_Am, 2);
            std_Duong = CoreFunctions.Tk_PopularStandardDeviation(soTinHieu_Duong);
            std_Duong = (float)Math.Round(std_Duong, 2);
            std_Am = CoreFunctions.Tk_PopularStandardDeviation(soTinHieu_Am);
            std_Am = (float)Math.Round(std_Am, 2);

            avg_valDuong = CoreFunctions.Tk_GetAverage(listValueDuong);
            avg_valDuong = (float)Math.Round(avg_valDuong, 2);
            avg_valAm = CoreFunctions.Tk_GetAverage(listValueAm);
            avg_valAm = (float)Math.Round(avg_valAm, 2);
            std_ValDuong = CoreFunctions.Tk_PopularStandardDeviation(listValueDuong);
            std_ValDuong = (float)Math.Round(std_ValDuong, 2);
            std_ValAm = CoreFunctions.Tk_PopularStandardDeviation(listValueAm);
            std_ValAm = (float)Math.Round(std_ValAm, 2);

            avg_Reward = CoreFunctions.Tk_GetAverage(listReward);
            avg_Reward = (float)Math.Round(avg_Reward, 2);
            std_Reward = CoreFunctions.Tk_PopularStandardDeviation(listReward);
            std_Reward= (float)Math.Round(std_Reward, 2);

            listContent = new List<string>();
            listContent.Add("[So Dinh/Break Dao Chieu]");
            listContent.Add("Loai\t\tCOUNT\t\tAVG\t\tSTD\t\t1D\t\t2D\t\t3D\t\t4D");

            listContent.Add("Duong\t\t" + soTinHieu_Duong.Count + "\t\t" + avg_Duong + "\t\t" + std_Duong
                + "\t\t" + listStatistic_Dinh[0][0] + "\t\t" + listStatistic_Dinh[0][1] + "\t\t" + listStatistic_Dinh[0][2]
                + "\t\t" + listStatistic_Dinh[0][3]);
            listContent.Add("Am\t\t" + soTinHieu_Am.Count + "\t\t" + avg_Am + "\t\t" + std_Am
                + "\t\t" + listStatistic_Dinh[1][0] + "\t\t" + listStatistic_Dinh[1][1] + "\t\t" + listStatistic_Dinh[1][2]
                + "\t\t" + listStatistic_Dinh[1][3]);

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Avg Break Value of MFI, RSI, IMI ]");
            listContent.Add("Loai\t\tAVG\t\tSTD");
            listContent.Add("Duong\t\t" + avg_valDuong + "\t\t" + std_ValDuong);
            listContent.Add("Am\t\t" + avg_valAm + "\t\t" + std_ValAm);

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Reward]");
            listContent.Add("Reward\t\tCOUNTB&S\tAVG\t\tSTD");
            listContent.Add("Reward\t\t" + listReward.Count + "\t\t" + avg_Reward + "\t\t" + std_Reward);

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Reward Duong/Am]");
            listContent.Add("Reward\t\tCOUNTB&S\tAVG\t\tSTD");
            avg_Duong = CoreFunctions.Tk_GetAverage(listReward_Duong);
            avg_Duong = (float)Math.Round(avg_Duong, 2);
            std_Duong = CoreFunctions.Tk_PopularStandardDeviation(listReward_Duong);
            std_Duong = (float)Math.Round(std_Duong, 2);
            listContent.Add("Duong\t\t\t" + listReward_Duong.Count + "\t\t" + avg_Duong + "\t\t" + std_Duong);

            avg_Am = CoreFunctions.Tk_GetAverage(listReward_Am);
            avg_Am = (float)Math.Round(avg_Am, 2);
            std_Am = CoreFunctions.Tk_PopularStandardDeviation(listReward_Am);
            std_Am = (float)Math.Round(std_Am, 2);
            listContent.Add("Am\t\t\t" + listReward_Am.Count + "\t\t" + avg_Am + "\t\t" + std_Am);

            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\Data\Testing_AVGRSIMFIIMI_Statistic_TinHieu.txt", listContent);
            #endregion
        }

        public string Testing_Cross2EMA_TinHieu(int chuky1 = 25, int chuky2 = 45
                            , bool flag_giaDieuChinh = false, string nameCPTest = "")
        {
            #region Biến
            int temp_int, id_mua = 0, id_ban = 0;
            bool flag_namCP = false;
            float temp_float;
            List<float> listReward = new List<float>();
            List<float> listReward_Duong = new List<float>();
            List<float> listReward_Am = new List<float>();
            List<float> pricesOfStock = new List<float>();
            List<float> EMA_1 = new List<float>();
            List<float> EMA_2 = new List<float>();
            List<int> listNgayNamGiuCP = new List<int>();

            if (chuky1 > chuky2)
            {
                temp_int = chuky1;
                chuky1 = chuky2;
                chuky2 = temp_int;
            }
            #endregion

            #region Demo
            foreach (CoPhieu CP in this._danhSachCoPhieu)
            {
                if (nameCPTest != "" && CP.TenCoPhieu != nameCPTest)
                    continue;
                if (flag_giaDieuChinh == false)
                    pricesOfStock = CP.DanhSachGiaDongCua;
                else
                    pricesOfStock = CP.DanhSachGiaDongCua_DieuChinh;

                EMA_1 = Indicators.EMA(pricesOfStock, chuky1);
                EMA_2 = Indicators.EMA(pricesOfStock, chuky2);
                flag_namCP = false;
                for (int i = Math.Min(EMA_1.Count, EMA_2.Count) - 5; i > 0; i--)
                {
                    if (flag_namCP == false && EMA_2[i + 1] > EMA_1[i + 1]
                        && EMA_2[i] < EMA_1[i])
                    {
                        flag_namCP = true;
                        id_mua = i;
                    }


                    else if (flag_namCP == true)
                    {
                        temp_float = (pricesOfStock[i] - pricesOfStock[id_mua]) / pricesOfStock[id_mua];
                        //if (temp_float <= -0.03f)
                        //{
                        //    flag_namCP = false;
                        //    listReward.Add(temp_float);
                        //    listReward_Am.Add(temp_float);
                        //    listNgayNamGiuCP.Add(id_mua - i);
                        //}
                        //else 
                            if (EMA_2[i + 1] < EMA_1[i + 1]
                            && EMA_2[i] > EMA_1[i])
                        {
                            flag_namCP = false;
                            id_ban = i;

                            listReward.Add(temp_float);
                            if (temp_float > 0)
                                listReward_Duong.Add(temp_float);
                            else
                                listReward_Am.Add(temp_float);
                            listNgayNamGiuCP.Add(id_mua - id_ban);
                        }
                    }

                }
            }
            #endregion

            #region Thống kê - ghi file
            /// result_string = "Chuky\tCount\tAvg\tStd\tCount+\tAvg+\tStd+\tCount-\tAvg-\tStd-
            /// \tCountD\tAvgD\tStdD
            
            string result_string = chuky1.ToString() + "_" + chuky2.ToString() + "\t";

            List<string> listContent = new List<string>();
            float avg_Duong, avg_Am, avg_Reward,
                std_Duong, std_Am, std_Reward;

            listContent.Add("[Reward]");
            listContent.Add("COUNTB&S\tAVG\t\tSTD");          
            avg_Reward = CoreFunctions.Tk_GetAverage(listReward);
            avg_Reward = (float)Math.Round(avg_Reward, 2);
            std_Reward = CoreFunctions.Tk_PopularStandardDeviation(listReward);
            std_Reward = (float)Math.Round(std_Reward, 2);
            listContent.Add(listReward.Count + "\t\t" + avg_Reward + "\t\t" + std_Reward);

            result_string += listReward.Count + "\t" + avg_Reward + "\t" + std_Reward + "\t";

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Reward Duong/Am]");
            listContent.Add("Reward\t\tCOUNTB&S\tAVG\t\tSTD");
            avg_Duong = CoreFunctions.Tk_GetAverage(listReward_Duong);
            avg_Duong = (float)Math.Round(avg_Duong, 2);
            std_Duong = CoreFunctions.Tk_PopularStandardDeviation(listReward_Duong);
            std_Duong = (float)Math.Round(std_Duong, 2);
            listContent.Add("Duong\t\t\t" + listReward_Duong.Count + "\t\t" + avg_Duong + "\t\t" + std_Duong);

            result_string += listReward_Duong.Count + "\t" + avg_Duong + "\t" + std_Duong+ "\t";

            avg_Am = CoreFunctions.Tk_GetAverage(listReward_Am);
            avg_Am = (float)Math.Round(avg_Am, 2);
            std_Am = CoreFunctions.Tk_PopularStandardDeviation(listReward_Am);
            std_Am = (float)Math.Round(std_Am, 2);
            listContent.Add("Am\t\t\t" + listReward_Am.Count + "\t\t" + avg_Am + "\t\t" + std_Am);

            result_string += listReward_Am.Count + "\t" + avg_Am + "\t" + std_Am + "\t";

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Ngay Nam Giu CP]");
            listContent.Add("COUNT\t\tAVG\t\tSTD");
            avg_Duong = CoreFunctions.Tk_GetAverage(listNgayNamGiuCP);
            avg_Duong = (float)Math.Round(avg_Duong, 2);
            std_Duong = CoreFunctions.Tk_PopularStandardDeviation(listNgayNamGiuCP);
            std_Duong = (float)Math.Round(std_Duong, 2);
            listContent.Add(listNgayNamGiuCP.Count + "\t\t" + avg_Duong + "\t\t" + std_Duong);

            result_string += listNgayNamGiuCP.Count + "\t" + avg_Duong + "\t" + std_Duong + "\t";

            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\Data\Testing_CrossEMA_TinHieu.txt", listContent);

            return result_string;
            #endregion
        }

        public void Testing_Cross2EMA_ToiUu()
        {
            List<string> listContent = new List<string>();
            string result = "";
            listContent.Add("Chuky\tCount\tAvg\tStd\tCount+\tAvg+\tStd+\tCount-\tAvg-\tStd-" +
             "\tCountD\tAvgD\tStdD");

            for (int i = 5; i <= 200; i += 3)
                for (int j = i + 5; j <= 200; j += 3)
                {
                    result = Testing_Cross2EMA_TinHieu(i, j);
                    listContent.Add(result);
                }

            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
              + @"\Data\Testing_CrossEMA_ToiUu.txt", listContent);
        }

        public void Testing_Histogram_Cross2EMA_TinHieuMua(int chuky1 = 13, int chuky2 = 34
            , int khoangcachToiThieu2dinhHistogram = 5)
        {
            #region Biến
            bool flag_Duong = false;
            int count = 0;
            List<string> listContent = new List<string>();
            List<float> MACD = new List<float>();
            List<float> signalLine = new List<float>();
            List<float> histogram = new List<float>();
            List<float> listSignalBuySell;
            List<float> priceOfStock = new List<float>();

            List<int> listIDNgay = new List<int>();
            List<int> temp = new List<int>();
            List<int> soTinHieu_Duong = new List<int>(); /// tín hiệu bán
            List<int> soTinHieu_Am = new List<int>(); /// tín hiệu mua

            List<float> listReward = new List<float>();
            List<float> listReward_Duong = new List<float>();
            List<float> listReward_Am = new List<float>();
            List<float> listTemp_float = new List<float>();
            int id_mua, id_ban, min;
            float temp_float;
            bool flag_DangGiuCP = false;
            List<float> EMA_1 = new List<float>();
            List<float> EMA_2 = new List<float>();
            List<int> listNgayNamGiu = new List<int>();
            #endregion

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                //priceOfStock = CP.DanhSachGiaDongCua_DieuChinh;
                priceOfStock = CP.DanhSachGiaDongCua;

                #region *** Tính  histogram
                EMA_1 = Indicators.EMA(priceOfStock, chuky1);
                EMA_2 = Indicators.EMA(priceOfStock, chuky2);
                histogram = new List<float>();

                for (int j = 0; j < EMA_2.Count; j++)
                    histogram.Add(EMA_1[j] - EMA_2[j]);
                listSignalBuySell = Indicators.GetSignalBuySell(histogram, khoangcachToiThieu2dinhHistogram);
                #endregion

                #region *** Statistic theo Historgram
                temp = new List<int>();

                if (listSignalBuySell[0] > 0)
                    flag_Duong = false;
                else
                    flag_Duong = true;

                for (int i = 0; i < listSignalBuySell.Count; i++)
                {
                    if (listSignalBuySell[i] > 0 && !flag_Duong)
                    {
                        flag_Duong = true;
                        temp = soTinHieu_Duong;
                        count = 0;
                        for (int j = i; j < listSignalBuySell.Count; j++)
                            if (listSignalBuySell[j] > 0)
                                count++;
                            else if (listSignalBuySell[j] < 0)
                            {
                                i = j;
                                break;
                            }
                        temp.Add(count);
                    }
                    else if (listSignalBuySell[i] < 0 && flag_Duong)
                    {
                        flag_Duong = false;
                        temp = soTinHieu_Am;
                        count = 0;
                        for (int j = i; j < listSignalBuySell.Count; j++)
                            if (listSignalBuySell[j] < 0)
                                count++;
                            else if (listSignalBuySell[j] > 0)
                            {
                                i = j;
                                break;
                            }
                        temp.Add(count);
                    }
                }
                #endregion

                #region  Tính theo giá trị đạt được khi tính toán theo tín hiệu histogram

                #region Mua CP khi histogram đang ở dưới 0 [có 3 đỉnh] bán khi có tín hiệu histogram dương đầu tiên
                flag_DangGiuCP = false;
                listTemp_float = new List<float>();
                listTemp_float = priceOfStock;
                id_mua = 0;
                min = Math.Min(500, listSignalBuySell.Count - 1);
                for (int i = min; i >= 0; i--)
                {
                    if (flag_DangGiuCP == false && listSignalBuySell[i] > 0)
                    {
                        count = 1;
                        for (int j = i - 1; j >= 0; j--)
                            if (listSignalBuySell[j] < 0)
                            {
                                i = j + 1;
                                break;
                            }
                            else if (listSignalBuySell[j] > 0)
                            {
                                count++;
                                if (count > 2)
                                {
                                    flag_DangGiuCP = true;
                                    i = j - 1;
                                    id_mua = j;
                                    break;
                                }
                            }
                            else if (flag_DangGiuCP == true)
                            {
                                temp_float = (listTemp_float[j] - listTemp_float[id_mua]) / listTemp_float[id_mua];
                                if (temp_float < -0.02f)
                                {
                                    flag_DangGiuCP = false;
                                    listReward.Add(temp_float);
                                    listReward_Am.Add(temp_float);
                                }
                            }

                    }
                    else if (flag_DangGiuCP == true && listSignalBuySell[i] < 0)
                    {
                        flag_DangGiuCP = false;
                        id_ban = i;
                        temp_float = (listTemp_float[id_ban] - listTemp_float[id_mua]) / listTemp_float[id_mua];

                        listNgayNamGiu.Add(id_mua - id_ban);

                        listReward.Add(temp_float);

                        if (temp_float > 0f)
                            listReward_Duong.Add(temp_float);
                        else
                            listReward_Am.Add(temp_float);
                    }
                }
                #endregion

                #region Mua CP khi histogram đang ở trên 0 [có 1 đỉnh] bán khi có tín hiệu histogram dương thứ 2
                //flag_DangGiuCP = false;

                //listTemp_float = priceOfStock;
                //id_mua = 0;
                //min = Math.Min(500, listSignalBuySell.Count - 1);

                //for (int i = min; i >= 0; i--)                
                //    if (flag_DangGiuCP == false && listSignalBuySell[i] < 0)
                //    {
                //        count = 1;
                //        int count_giam = 0;
                //        for (int j = i; j > 0; j--)
                //        {
                //            if (histogram[j] > histogram[j - 1] && histogram[j - 1] > 0)
                //                count_giam++;
                //            else if (histogram[j] < 0)
                //            {
                //                count_giam = 0;
                //                i = j - 1;
                //                if (flag_DangGiuCP == true)
                //                {
                //                    flag_DangGiuCP = false;
                //                    id_ban = j - 1;
                //                    listNgayNamGiu.Add(id_mua - id_ban);
                //                    temp_float = (listTemp_float[id_ban] - listTemp_float[id_mua]) / listTemp_float[id_mua];
                //                    listReward.Add(temp_float);
                //                    if (temp_float > 0)
                //                        listReward_Duong.Add(temp_float);
                //                    else
                //                        listReward_Am.Add(temp_float);
                //                }
                //                break;
                //            }
                //            else if (flag_DangGiuCP == false
                //                && count_giam >= 5 && histogram[j] < histogram[j - 1])
                //            {
                //                flag_DangGiuCP = true;
                //                id_mua = j - 1;
                //                count_giam = 0;
                //            }
                //            else if (flag_DangGiuCP == true && listSignalBuySell[j] < 0)
                //            {
                //                flag_DangGiuCP = false;
                //                count++;
                //                id_ban = j - 1;
                //                listNgayNamGiu.Add(id_mua - id_ban);
                //                temp_float = (listTemp_float[id_ban] - listTemp_float[id_mua]) / listTemp_float[id_mua];
                //                listReward.Add(temp_float);
                //                if (temp_float > 0)
                //                    listReward_Duong.Add(temp_float);
                //                else
                //                    listReward_Am.Add(temp_float);

                //                i = j - 1;
                //                break;
                //            }
                //        }
                //    }                   

                #endregion
                #endregion
            }

            #region Tính toán thống kê và ghi file
            List<List<float>> listStatistic_Dinh = new List<List<float>>();
            List<List<int>> listCountTinHieu = new List<List<int>>();
            listCountTinHieu.Add(soTinHieu_Duong);
            listCountTinHieu.Add(soTinHieu_Am);

            foreach (List<int> listValues in listCountTinHieu)
            {
                listStatistic_Dinh.Add(new List<float>());
                count = 0;
                for (int i = 1; i <= 4; i++)
                {
                    for (int j = 0; j < listValues.Count; j++)
                        if (listValues[j] == i)
                            count++;
                    listStatistic_Dinh[listStatistic_Dinh.Count - 1]
                        .Add((float)Math.Round((float)count / listValues.Count, 2));
                }
            }

            float avg_Duong, avg_Am, std_Duong, std_Am;
            avg_Duong = CoreFunctions.Tk_GetAverage(soTinHieu_Duong);
            avg_Duong = (float)Math.Round(avg_Duong, 2);
            avg_Am = CoreFunctions.Tk_GetAverage(soTinHieu_Am);
            avg_Am = (float)Math.Round(avg_Am, 2);
            std_Duong = CoreFunctions.Tk_PopularStandardDeviation(soTinHieu_Duong);
            std_Duong = (float)Math.Round(std_Duong, 2);
            std_Am = CoreFunctions.Tk_PopularStandardDeviation(soTinHieu_Am);
            std_Am = (float)Math.Round(std_Am, 2);

            float avg_Reward = CoreFunctions.Tk_GetAverage(listReward);
            avg_Reward = (float)Math.Round(avg_Reward, 2);
            float std_Reward = CoreFunctions.Tk_PopularStandardDeviation(listReward);
            std_Reward = (float)Math.Round(std_Reward, 2);


            listContent = new List<string>();
            listContent.Add("Loai\t\tCOUNT\t\tAVG\t\tSTD\t\t1D\t\t2D\t\t3D\t\t4D");

            listContent.Add("Duong\t\t" + soTinHieu_Duong.Count + "\t\t" + avg_Duong + "\t\t" + std_Duong
                + "\t\t" + listStatistic_Dinh[0][0] + "\t\t" + listStatistic_Dinh[0][1] + "\t\t" + listStatistic_Dinh[0][2]
                + "\t\t" + listStatistic_Dinh[0][3]);
            listContent.Add("Am\t\t" + soTinHieu_Am.Count + "\t\t" + avg_Am + "\t\t" + std_Am
                + "\t\t" + listStatistic_Dinh[1][0] + "\t\t" + listStatistic_Dinh[1][1] + "\t\t" + listStatistic_Dinh[1][2]
                + "\t\t" + listStatistic_Dinh[1][3]);

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Reward]");
            listContent.Add("Reward\t\tCOUNTB&S\tAVG\t\tSTD");
            listContent.Add("Reward\t\t" + listReward.Count + "\t\t" + avg_Reward + "\t\t" + std_Reward);

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Reward Duong/Am]");
            listContent.Add("Reward\t\tCOUNTB&S\tAVG\t\tSTD");
            avg_Duong = CoreFunctions.Tk_GetAverage(listReward_Duong);
            avg_Duong = (float)Math.Round(avg_Duong, 2);
            std_Duong = CoreFunctions.Tk_PopularStandardDeviation(listReward_Duong);
            std_Duong = (float)Math.Round(std_Duong, 2);
            listContent.Add("Duong\t\t\t" + listReward_Duong.Count + "\t\t" + avg_Duong + "\t\t" + std_Duong);

            avg_Am = CoreFunctions.Tk_GetAverage(listReward_Am);
            avg_Am = (float)Math.Round(avg_Am, 2);
            std_Am = CoreFunctions.Tk_PopularStandardDeviation(listReward_Am);
            std_Am = (float)Math.Round(std_Am, 2);
            listContent.Add("Am\t\t\t" + listReward_Am.Count + "\t\t" + avg_Am + "\t\t" + std_Am);

            listContent.Add("\r\n-----------------------------------------------------\r\n");
            listContent.Add("[Ngay Nam Giu CP]");
            listContent.Add("COUNT\t\tAVG\t\tSTD");
            avg_Duong = CoreFunctions.Tk_GetAverage(listNgayNamGiu);
            avg_Duong = (float)Math.Round(avg_Duong, 2);
            std_Duong = CoreFunctions.Tk_PopularStandardDeviation(listNgayNamGiu);
            std_Duong = (float)Math.Round(std_Duong, 2);
            listContent.Add(listNgayNamGiu.Count + "\t\t" + avg_Duong + "\t\t" + std_Duong);

            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\Data\Testing_HistogramCrossEMA_TinHieu.txt", listContent);
            #endregion
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="chukyMACD"></param>
        /// <param name="soNgayCachBreak"></param>
        /// <param name="soNgaySMA"></param>
        /// <param name="idCase">1: DEMA. 2: TEMA</param>
        public void Testing_MACD_TinHieuMua_KiemTra(int chukyMACD, int soNgayCachBreak, int soNgaySMA, int idCase)
        {
            List<List<float>> listCount = new List<List<float>>();
            List<List<float>> listchechlech = new List<List<float>>();
            List<string> listContent = new List<string>();
            List<float> MACD = new List<float>();
            List<float> signalLine = new List<float>();
            List<float> listSMA = new List<float>();
            List<int> listidNgay = new List<int>();
            List<int> listBreak = new List<int>();

            int count;
            int ngaySMA = soNgaySMA;
            string text = "";
            float percent = 0f, avg, std, avgGia, stdGia, percentGia;

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                switch (idCase)
                {
                    case 1:
                        {
                            Indicators.MACD_smoothDEMA(CP.DanhSachGiaDongCua, 12, 26, chukyMACD, ref MACD, ref signalLine);
                            break;
                        }
                    case 2:
                        {
                            Indicators.MACD_smoothTEMA(CP.DanhSachGiaDongCua, 12, 26, chukyMACD, ref MACD, ref signalLine);
                            break;
                        }
                }

                listidNgay = Indicators.MACD_XacDinhListTinHieuMua(MACD, signalLine, soNgayCachBreak);

                listCount.Add(new List<float>());
                listBreak.Add(listidNgay.Count);
                listchechlech.Add(new List<float>());

                /// Kiểm tra với SMA 20. cắt MACD có đồng thuận với tăng của SMA 20
                listSMA = Indicators.SMA(CP.DanhSachGiaDongCua, ngaySMA);
                percent = 0f;
                foreach (int idNgay in listidNgay)
                {
                    count = 0;
                    for (int i = idNgay - 1; i >= 0; i--)
                        if (i < listSMA.Count
                            && Math.Log(listSMA[i] / listSMA[i + 1]) >= 0.01f)
                            //&& listSMA[i] > listSMA[i + 1])
                            count++;
                        else
                            break;
                    if (count > 0)
                    {
                        listCount[listCount.Count - 1].Add(count);
                        percent = (float)Math.Log(listSMA[idNgay - count] / listSMA[idNgay]);
                        listchechlech[listchechlech.Count - 1].Add(percent);
                    }
                }
            }
            listContent.Add("CP\tCountBreak\t%++\tAvgNgay\tStdNgay\tAvgGia\tStdGia");

            count = 0;
            percent = 0f;
            percentGia = 0f;
            for (int i = 0; i < listCount.Count; i++)
            {
                text = "";
                if (listBreak[i] > 0 && listCount[i].Count > 0)
                {
                    avg = (float)Math.Round(CoreFunctions.Tk_GetAverage(listCount[i]), 2);
                    avgGia = (float)Math.Round(CoreFunctions.Tk_GetAverage(listchechlech[i]) * 100, 0);
                    stdGia = (float)Math.Round(CoreFunctions.Tk_PopularStandardDeviation(listchechlech[i]) * 100, 0);
                    std = (float)Math.Round(CoreFunctions.Tk_PopularStandardDeviation(listCount[i]), 2);

                    percentGia += avgGia;

                    count++;
                    percent += (float)listCount[i].Count / listBreak[i];

                    text = _danhSachCoPhieu[i].TenCoPhieu + "\t" + listBreak[i].ToString();

                    text += "\t\t" + (float)Math.Round((float)listCount[i].Count * 100 / listBreak[i], 0) + "%";
                    text += "\t" + avg.ToString();
                    text += "\t\t" + std.ToString();
                    text += "\t\t" + avgGia.ToString() + "%";
                    text += "\t\t" + stdGia.ToString() + "%";
                }
                else
                    text += _danhSachCoPhieu[i].TenCoPhieu;
                listContent.Add(text);
            }

            percent = (float)Math.Round(percent / count, 2);
            percentGia = (float)Math.Round(percentGia / count, 2);

            listContent.Insert(0, "---------------------------------------------------");
            listContent.Insert(0, "Total %Tang: " + (percent * 100) + "% -- %ChechlechGia: " + (percentGia * 1) + "%");
            listContent.Insert(0, "Chu ky MACD : " + chukyMACD + " -- " + "So ngay cach Break: " + soNgayCachBreak
                + " -- Chu ky SMA: " + ngaySMA);
            listContent.Insert(0, this.HeaderFile);

            string path = "";
            switch (idCase)
            {
                case 1:
                    {
                        path = "Testing_Indicators_KiemTraTHMuaDEMA_MACD.txt";
                        break;
                    }
                case 2:
                    {
                        path = "Testing_Indicators_KiemTraTHMuaTEMA_MACD.txt";
                        break;
                    }
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, path, listContent);
        }

        #region * Testing Indicator
        public void Testing_MACD_TinHieuMua(int chukyMACD, int KhoangCachBreak, int soNgayBanCP, ref List<bool> MACD_DEMA
                                           , ref List<bool> MACD_TEMA, ref List<int> MACD_histogram, ref List<int> histogram_sodinh)
        {
            #region Biến
            List<string> listContent = new List<string>();
            List<string> listContentDEMA = new List<string>();
            List<string> listContentTEMA = new List<string>();
            List<float> MACD = new List<float>();
            List<float> signalLine = new List<float>();
            List<float> histogram = new List<float>();
            List<int> listIDNgay = new List<int>();
            MACD_DEMA = new List<bool>();
            MACD_TEMA = new List<bool>();
            MACD_histogram = new List<int>();
            histogram_sodinh = new List<int>();

            string chechlech = "", text;
            float giachechlech, tbDEMA = 0, tbTEMA = 0;
            int idNgay, countDEMA = 0, countTEMA = 0, posDEMA = 0, posTEMA = 0;

            List<float> priceOfStock = new List<float>();

            bool flag = false;
            #endregion

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                MACD_DEMA.Add(false);
                MACD_TEMA.Add(false);
                MACD_histogram.Add(100);
                histogram_sodinh.Add(0);
                priceOfStock = CP.DanhSachGiaDongCua_DieuChinh;

                #region *** Tính MACD_smoothDEMA
                MACD = new List<float>();
                signalLine = new List<float>();
                Indicators.MACD_smoothDEMA(priceOfStock, 12, 26, chukyMACD, ref MACD, ref signalLine);
                flag = false;

                if (MACD.Count > KhoangCachBreak)
                {
                    idNgay = -1;
                    listIDNgay = new List<int>();
                    listIDNgay = Indicators.MACD_XacDinhListTinHieuMua(MACD, signalLine, KhoangCachBreak);
                    if (listIDNgay.Count != 0)
                        idNgay = listIDNgay[0];

                    if (idNgay > -1)
                    {
                        text = CP.TenCoPhieu + "\t" + CP.DanhSachNgayGiaoDich[idNgay].NgayGiaoDich_Str;
                        if (idNgay > soNgayBanCP)
                        {
                            giachechlech = (float)Math.Round(Math.Log(
                                CP.DanhSachNgayGiaoDich[idNgay - soNgayBanCP].GiaDongCua / CP.DanhSachNgayGiaoDich[idNgay].GiaDongCua), 2);
                            giachechlech = giachechlech * 100;
                            text += "\t\t" + giachechlech.ToString() + "%";
                            text += "\t\tEND";

                            tbDEMA += giachechlech;
                            if (giachechlech > 0.0f)
                                posDEMA++;
                            countDEMA++;
                        }
                        else
                            MACD_DEMA[MACD_DEMA.Count - 1] = true;

                        listContentDEMA.Add(text);
                        flag = true;
                    }
                }
                #endregion

                #region *** Tính MACD_smoothTEMA
                MACD = new List<float>();
                signalLine = new List<float>();
                ///Indicators.MACD_smoothTEMA(priceOfStock, 12, 26, chukyMACD, ref MACD, ref signalLine);
                Indicators.MACD(priceOfStock, 12, 26, chukyMACD, ref MACD, ref signalLine);
                if (MACD.Count > KhoangCachBreak)
                {
                    idNgay = -1;
                    listIDNgay = new List<int>();
                    listIDNgay = Indicators.MACD_XacDinhListTinHieuMua(MACD, signalLine, KhoangCachBreak);
                    if (listIDNgay.Count != 0)
                        idNgay = listIDNgay[0];

                    if (idNgay > -1)
                    {
                        text = CP.TenCoPhieu + "\t" + CP.DanhSachNgayGiaoDich[idNgay].NgayGiaoDich_Str;
                        if (idNgay > soNgayBanCP)
                        {
                            giachechlech = (float)Math.Round(Math.Log(
                                CP.DanhSachNgayGiaoDich[idNgay - soNgayBanCP].GiaDongCua / CP.DanhSachNgayGiaoDich[idNgay].GiaDongCua), 2);
                            giachechlech = giachechlech * 100;
                            text += "\t\t" + giachechlech.ToString() + "%";
                            text += "\t\tEND";

                            tbTEMA += giachechlech;
                            if (giachechlech > 0.0f)
                                posTEMA++;
                            countTEMA++;
                        }
                        else
                            MACD_TEMA[MACD_TEMA.Count - 1] = true;

                        listContentTEMA.Add(text);
                        if (flag == false)
                            chechlech += CP.TenCoPhieu + "  ";
                    }
                    else
                        if (flag == true)
                            chechlech += CP.TenCoPhieu + "  ";
                }
                #endregion

                #region *** Tính Signal Buy theo Historgram
                histogram = new List<float>();

                for (int j = 0; j < signalLine.Count; j++)
                    histogram.Add(MACD[j] - signalLine[j]);

                List<float> listSignalBuySell = Indicators.GetSignalBuySell(histogram);
                int temp_int = 0, count_SoTinHieuMua = 0;
                for (int j = 0; j < listSignalBuySell.Count; j++)
                    if (listSignalBuySell[j] > 0)
                    {
                        temp_int = j;
                        count_SoTinHieuMua++;
                        for (int k = j + 1; k < listSignalBuySell.Count; k++)
                            if (listSignalBuySell[k] < 0 || histogram[k] > 0)
                            {
                                break;
                            }
                            else if (listSignalBuySell[k] > 0)
                            {
                                //temp_int = k;
                                count_SoTinHieuMua++;
                            }

                        MACD_histogram[MACD_histogram.Count - 1] = temp_int;
                        histogram_sodinh[histogram_sodinh.Count - 1] = count_SoTinHieuMua;
                        break;
                    }
                #endregion
            }

            listContentDEMA.Sort(CoreFunctions.Compare_String_THMua);
            listContentTEMA.Sort(CoreFunctions.Compare_String_THMua);

            listContent.Add(this.HeaderFile);
            listContent.Add("Chu ky: " + chukyMACD.ToString());
            listContent.Add("Chech lech: " + chechlech);

            listContent.Add("---------------------------- DEMA ------------------------------");
            listContent.Add("**** Soluong: " + listContentDEMA.Count.ToString()
                + "\t\tTong:" + Math.Round((tbDEMA), 0).ToString() + "%"
                + "\t\t%Tang: " + Math.Round(((float)posDEMA / countDEMA) * 100, 0).ToString() + "%");
            listContent.AddRange(listContentDEMA);
            listContent.Add("");

            listContent.Add("---------------------------- TEMA ------------------------------");
            listContent.Add("**** Soluong: " + listContentTEMA.Count.ToString()
                + "\t\tTong:" + Math.Round((tbTEMA), 0).ToString() + "%"
                + "\t\t%Tang: " + Math.Round(((float)posTEMA / countTEMA) * 100, 0).ToString() + "%");
            listContent.AddRange(listContentTEMA);

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_Indicators_THMua_MACD.txt", listContent);
        }

        public List<int> Testing_SoNgayCachCrossEMA(int soNgayEMA1, int soNgayEMA2)
        {
            List<int> listResult = new List<int>();
            foreach (CoPhieu cp in _danhSachCoPhieu)
            {
                listResult.Add(cp.TinhSoNgayCachCrossEMA(soNgayEMA1, soNgayEMA2));
            }
            return listResult;
        }

        public List<float> Testing_MFI_MoneyFlowIndex(int soNgayTest)
        {
            List<float> listMFI = new List<float>();
            List<string> listContent = new List<string>();
            string text = "";
            float MFI;
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("So Ngay Test: " + soNgayTest);
            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                text = CP.TenCoPhieu;
                MFI = CP.TinhDanhSachChiSo_MoneyFlowIndex_MFI(soNgayTest);
                MFI = (float)Math.Round(MFI, 0);
                text += "\t" + MFI;
                listContent.Add(text);
                listMFI.Add(MFI);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_Indicators_MFI.txt", listContent);
            return listMFI;
        }

        public List<float> Testing_RSI_RelativeStrengIndex(int soNgayTest)
        {
            List<float> listRSI = new List<float>();
            List<string> listContent = new List<string>();
            string text = "";
            float RSI;
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("So Ngay Test: " + soNgayTest);
            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                text = CP.TenCoPhieu;
                RSI = CP.TinhDanhSachChiSo_RelativeStrengIndex_RSI(soNgayTest);
                RSI = (float)Math.Round(RSI, 0);
                text += "\t" + RSI;
                listContent.Add(text);
                listRSI.Add(RSI);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_Indicators_RSI.txt", listContent);
            return listRSI;
        }

        public List<float> Testing_IMI_IntradayMomentumIndex(int soNgayTest)
        {
            List<float> listIMI = new List<float>();
            List<string> listContent = new List<string>();
            string text = "";
            float IMI;
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("So Ngay Test: " + soNgayTest);
            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                text = CP.TenCoPhieu;
                IMI = CP.TinhDanhSachChiSo_IntradayMomentumIndex_IMI(soNgayTest, 0);
                text += "\t" + IMI;
                listContent.Add(text);
                listIMI.Add(IMI);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_Indicators_IMI.txt", listContent);
            return listIMI;
        }

        public void Testing_MFI_RSI(int soNgayMFI, int soNgayRSI)
        {
            List<float> listRSI = new List<float>();
            List<string> listContent = new List<string>();
            string text = "";
            float RSI, MFI;
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("So Ngay MFI: " + soNgayMFI + "\t [20, 80]");
            listContent.Add("So Ngay RSI: " + soNgayRSI + "\t [30, 70]");
            listContent.Add("");
            listContent.Add("CP\t\tGia\t\tMFI\t\tRSI");
            listContent.Add("------------------------------------");
            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                text = CP.TenCoPhieu;
                MFI = CP.TinhDanhSachChiSo_MoneyFlowIndex_MFI(soNgayMFI);
                RSI = CP.TinhDanhSachChiSo_RelativeStrengIndex_RSI(soNgayRSI);
                text += "\t\t" + CP.DanhSachGiaDongCua[0] + "\t\t" + MFI + "\t\t" + RSI;
                if (MFI <= 20 || RSI <= 30)
                    text += "\t\tX";
                listContent.Add(text);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_Indicators_MFI_RSI.txt", listContent);
        }

        public void Testing_VNIndex_MFI_RSI(int soNgayMFI, int soNgayRSI)
        {
            int index = this.DanhSachTenCoPhieu.IndexOf("^VNINDEX");
            List<string> content = new List<string>();
            string row = "" ;
            for (int i = 0; i < _danhSachCoPhieu[index].DanhSachGiaCaoNhat.Count - 100; i++)
            {
                int count_morethan70 = 0, count_lessthan30 = 0, count_05 = 0, count_other = 0;
                float score;
                foreach (CoPhieu cp in this.DanhSachCoPhieu_List)
                {
                    if (cp.DanhSachNgayGiaoDich.Count > i + 50)
                    {
                        score = cp.TinhDanhSachChiSo_RelativeStrengIndex_RSI(soNgayRSI, i);
                        if (score >= 70f) count_morethan70++;
                        else if (score >= 50f) count_05++;
                        else if (score <= 30f) count_lessthan30++;
                        else count_other++;
                    }
                }
                row = _danhSachCoPhieu[index].DanhSachGiaDongCua[i] + "\t" +_danhSachCoPhieu[index].DanhSachNgayGiaoDich_String[i]
                    + "\t" + count_morethan70 + "\t" + count_05
                    + "\t" + count_other + "\t" + count_lessthan30;

                count_morethan70 = 0; count_lessthan30 = 0; count_05 = 0; count_other = 0;

                foreach (CoPhieu cp in this.DanhSachCoPhieu_List)
                {
                    if (cp.DanhSachNgayGiaoDich.Count > i + 50)
                    {
                        score = cp.TinhDanhSachChiSo_MoneyFlowIndex_MFI(soNgayMFI, i);
                        if (score >= 80f) count_morethan70++;
                        else if (score >= 50f) count_05++;
                        else if (score <= 20f) count_lessthan30++;
                        else count_other++;
                    }
                }
                row += "\t" + count_morethan70 + "\t" + count_05
                   + "\t" + count_other + "\t" + count_lessthan30;
                content.Add(row);
                row = "";
            }

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_VNINDEX_RSI_MSI.txt", content);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="soNgay"></param>
        /// <returns>Chêch lệch % giữa giá và đường dưới (gần nhất)</returns>
        public List<float> Testing_BollingerBand(int soNgay, ref List<float> listDoRong)
        {
            List<float> DuongGiua = new List<float>();
            List<float> DuongTren = new List<float>();
            List<float> DuongDuoi = new List<float>();
            List<float> listResult = new List<float>();
            listDoRong = new List<float>();

            List<string> listContent = new List<string>();
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("So Ngay: " + soNgay);
            string text = "TenCP\t\tValues\tUpper\t\tCenter\tLower";
            listContent.Add(text);
            int len;
            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                listResult.Add(0f);
                listDoRong.Add(0f);
                Indicators.BollingerBand(CP.DanhSachGiaDongCua, 20, ref DuongGiua, ref DuongTren, ref DuongDuoi);
                len = DuongTren.Count - 1;
                if (len > 0)
                {
                    text = CP.TenCoPhieu + "\t\t" + CP.DanhSachGiaDongCua[0]
                        + "\t\t" + DuongTren[0] + "\t\t" + DuongGiua[0] + "\t\t" + DuongDuoi[0];
                    if (CP.DanhSachGiaDongCua[0] <= DuongDuoi[0])
                    {
                        text += "\t\tX";

                    }
                    listResult[listResult.Count - 1] = ((float)Math.Round(CP.DanhSachGiaDongCua[0] / DuongDuoi[0], 2) - 1);
                    listDoRong[listDoRong.Count - 1] = ((float)Math.Round(DuongTren[0] / DuongDuoi[0], 2) - 1);
                    listContent.Add(text);
                }
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_Indicators_BollingerBands.txt", listContent);
            return listResult;
        }

        public void Testing_BollingerBand_KiemTraDoChinhXac(int soNgay, int soNgayTest)
        {
            List<float> DuongGiua = new List<float>();
            List<float> DuongTren = new List<float>();
            List<float> DuongDuoi = new List<float>();

            List<string> listContent = new List<string>();

            listContent.Add("So Ngay: " + soNgay + " -- So Ngay Test: " + soNgayTest);
            string text = "TenCP\t\tCountP\tCount\t\tAvgP\t\tAvgValue";
            listContent.Add(text);

            int len, count, countPositive, countAll = 0, countPositiveAll = 0, countNegativeALL = 0;
            float sum, sumPositiveAll = 0, sumAll = 0, temp = 0, t1 = 0, sumNegativeAll = 0;
            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                Indicators.BollingerBand(CP.DanhSachGiaDongCua, 20, ref DuongGiua, ref DuongTren, ref DuongDuoi);
                len = DuongTren.Count - 1;
                count = 0;
                countPositive = 0;
                sum = 0;

                if (len > 0)
                {
                    for (int i = soNgayTest; i < DuongDuoi.Count; i++)
                        if (CP.DanhSachGiaDongCua[i] <= DuongDuoi[i] //// phần thay đổi điều kiện để kiểm tra: VD: giá > 15k && khoảng cách 2 biên > 10%
                            && CP.DanhSachGiaDongCua[i] > 25f
                            //&& CP.DanhSachGiaDongCua[i] < 25f 
                            && Math.Log(DuongTren[i] / DuongDuoi[i]) > 0.1f
                            )
                        {
                            count++;
                            countAll++;
                            temp = (float)Math.Round((CP.DanhSachGiaDongCua[i - soNgayTest] - CP.DanhSachGiaDongCua[i]) / CP.DanhSachGiaDongCua[i], 2);

                            sum += temp;
                            sumAll += temp;
                            if (CP.DanhSachGiaDongCua[i - soNgayTest] > CP.DanhSachGiaDongCua[i])
                            {
                                countPositive++;
                                countPositiveAll++;
                                sumPositiveAll += temp;
                            }
                            else
                            {
                                countNegativeALL++;
                                sumNegativeAll += temp;
                            }
                        }
                }

                if (count != 0)
                {
                    if (countPositive != 0)
                        text = CP.TenCoPhieu + "\t\t" + countPositive + "\t\t" + count + "\t\t" + (float)Math.Round((float)countPositive * 100 / count, 0)
                            + "%" + "\t\t" + Math.Round((float)sum * 100 / count, 0) + "%";
                    else
                        text = CP.TenCoPhieu + "\t\t" + countPositive + "\t\t" + count + "\t\t0"
                            + "%" + "\t\t" + Math.Round((float)sum * 100 / count, 0) + "%";


                    t1++;
                }
                else
                    text = CP.TenCoPhieu + "\t\t0\t\t0";
                listContent.Add(text);
            }

            text = "All count: " + countAll + " -- " + "%Poss: " + (float)Math.Round((float)countPositiveAll * 100 / countAll, 0) + "%"
                + " -- AvgPoss: " + (float)Math.Round((float)sumPositiveAll * 100 / countPositiveAll, 0)
                + "% -- AvgNeg: " + (float)Math.Round((float)sumNegativeAll * 100 / countNegativeALL, 0)
                + "% -- AvgAll: " + (float)Math.Round((float)sumAll * 100 / countAll, 0) + "%";
            listContent.Insert(1, text);
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_Indicators_BollingerBands_KiemTraTuongLai.txt", listContent);
        }

        public void Testing_PSAR(int soNgay, ref List<float> listAfd0, ref List<float> listAfd1)
        {
            listAfd0 = new List<float>();
            listAfd1 = new List<float>();

            List<float> AFD = new List<float>();
            List<string> listContent = new List<string>();
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("So Ngay: " + soNgay);
            listContent.Add("CP\t\tGia\t\tSAR0\t\tSAR1");
            string text = "";
            float afd0, afd1;

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                AFD = CP.TinhDanhSachChiSo_PSAR(soNgay);
                afd0 = AFD[0];
                afd1 = AFD[1];

                afd0 = (float)Math.Round(afd0, 1);
                afd1 = (float)Math.Round(afd1, 1);

                listAfd0.Add(afd0);
                listAfd1.Add(afd1);

                text = CP.TenCoPhieu + "\t\t" + CP.DanhSachGiaDongCua[0] + "\t\t" + afd0.ToString()
                    + "\t\t" + afd1.ToString();
                if (CP.DanhSachGiaDongCua[0] >= afd0 && CP.DanhSachGiaDongCua[0] <= afd1)
                {
                    text += "\t\tX";

                }

                listContent.Add(text);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_Indicators_PSAR.txt", listContent);


        }

        public void Testing_PSAR_KiemTra(int soNgay = 5, int soNgayTest = 5)
        {
            List<float> AFD = new List<float>();
            float afd0, afd1;
            List<string> listContent = new List<string>();
            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("So Ngay: " + soNgay);
            listContent.Add("CP\t\tCount\t\t%Pos\t\t%AvgValPoss\tAvgValAll");
            string text = "";
            int countPos = 0, countEachAll = 0, countAll = 0, countEachPos = 0;
            float sumPos = 0f, sumAll = 0f, temp, sumEachAll = 0f, sumEachPoss = 0f;
            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                countEachPos = 0; countEachAll = 0;
                sumEachAll = 0f; sumEachPoss = 0f;

                AFD = CP.TinhDanhSachChiSo_PSAR(soNgay);
                for (int i = soNgayTest + 1; i < AFD.Count - 1; i++)
                {
                    afd0 = AFD[i];
                    afd1 = AFD[i + 1];

                    afd0 = (float)Math.Round(afd0, 1);
                    afd1 = (float)Math.Round(afd1, 1);

                    if (CP.DanhSachGiaDongCua[i] >= afd0 && CP.DanhSachGiaDongCua[i] <= afd1)
                    {
                        countAll++;
                        countEachAll++;

                        temp = CP.DanhSachGiaDongCua[i - soNgayTest] / CP.DanhSachGiaDongCua[i] - 1;
                        temp = (float)Math.Round(temp * 100, 0);

                        sumAll += temp;
                        sumEachAll += temp;

                        if (temp > 0)
                        {
                            countPos++;
                            countEachPos++;

                            sumPos += temp;
                            sumEachPoss += temp;
                        }
                    }
                }
                if (countEachAll > 0)
                    text = CP.TenCoPhieu + "\t\t" + countEachAll + "\t\t" + (float)Math.Round((float)countEachPos / countEachAll * 100, 0) + "%\t\t"
                           + (float)Math.Round((float)sumEachPoss / countEachPos, 0) + "%\t\t\t"
                           + (float)Math.Round((float)sumEachAll / countEachAll, 0) + "%";
                else
                    text = CP.TenCoPhieu + "\t\t0";
                listContent.Add(text);

            }
            text = "CountAll: " + countAll + " -- " + "%Poss: " + (float)Math.Round((float)countPos / countAll * 100, 0)
                   + "% -- AvgValPoss: " + (float)Math.Round((float)sumPos / countPos, 0)
                   + "% -- AvgValAll: " + +(float)Math.Round((float)sumAll / countAll, 0) + "%";
            listContent.Insert(2, text);
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_Indicators_PSAR_KiemTra.txt", listContent);
        }

        public void Testing_PSARBollinger_KiemTra(int soNgay = 5, int soNgayTest = 5, int soNgayCachBB_PSAR = 5)
        {
            List<float> AFD = new List<float>();
            List<float> DuongGiua = new List<float>();
            List<float> DuongTren = new List<float>();
            List<float> DuongDuoi = new List<float>();
            List<string> listContent = new List<string>();

            int countPos = 0, countEachAll = 0, countAll = 0, countEachPos = 0, k;
            float sumPos = 0f, sumAll = 0f, temp, sumEachAll = 0f, sumEachPoss = 0f;
            float afd0, afd1;
            bool flag, flag_temp, flag_now;
            string text = "";

            listContent.Add(CoreFunctions.HeaderFile);
            listContent.Add("So Ngay: " + soNgay);
            listContent.Add("CP\t\tCount\t\t%Pos\t\t%AvgValPoss\tAvgValAll");

            foreach (CoPhieu CP in _danhSachCoPhieu)
            {
                countEachPos = 0; countEachAll = 0;
                sumEachAll = 0f; sumEachPoss = 0f;

                AFD = CP.TinhDanhSachChiSo_PSAR(soNgay);
                Indicators.BollingerBand(CP.DanhSachGiaDongCua, 20, ref DuongGiua, ref DuongTren, ref DuongDuoi);

                for (int i = soNgayTest + soNgayCachBB_PSAR; i < DuongDuoi.Count - soNgayCachBB_PSAR; i++)
                {
                    afd0 = AFD[i];
                    afd1 = AFD[i + 1];

                    afd0 = (float)Math.Round(afd0, 1);
                    afd1 = (float)Math.Round(afd1, 1);
                    flag = false;
                    flag_temp = false;
                    flag_now = false;

                    if (CP.DanhSachGiaDongCua[i] >= afd0 && CP.DanhSachGiaDongCua[i] <= afd1)
                    {
                        for (k = 0; k < soNgayCachBB_PSAR; k++)
                        {
                            if (CP.DanhSachGiaDongCua[i + k] <= DuongDuoi[i + k])
                            {
                                flag = true;
                                break;
                            }
                            if (CP.DanhSachGiaDongCua[i - k] <= DuongDuoi[i - k])
                            {
                                flag = true;
                                i = i - k;
                                flag_temp = true;
                                break;
                            }
                        }

                        if (flag == true)
                        {
                            countAll++;
                            countEachAll++;

                            temp = CP.DanhSachGiaDongCua[i - soNgayTest] / CP.DanhSachGiaDongCua[i] - 1;
                            temp = (float)Math.Round(temp * 100, 0);

                            sumAll += temp;
                            sumEachAll += temp;

                            if (temp > 0)
                            {
                                countPos++;
                                countEachPos++;

                                sumPos += temp;
                                sumEachPoss += temp;
                            }
                            if (flag_temp == true)
                                i += k;
                        }
                    }
                }
                if (countEachAll > 0)
                    text = CP.TenCoPhieu + "\t\t" + countEachAll + "\t\t" + (float)Math.Round((float)countEachPos / countEachAll * 100, 0) + "%\t\t"
                           + (float)Math.Round((float)sumEachPoss / countEachPos, 0) + "%\t\t\t"
                           + (float)Math.Round((float)sumEachAll / countEachAll, 0) + "%";
                else
                    text = CP.TenCoPhieu + "\t\t0";
                listContent.Add(text);
            }

            text = "CountAll: " + countAll + " -- " + "%Poss: " + (float)Math.Round((float)countPos / countAll * 100, 0)
                   + "% -- AvgValPoss: " + (float)Math.Round((float)sumPos / countPos, 0)
                   + "% -- AvgValAll: " + +(float)Math.Round((float)sumAll / countAll, 0) + "%";
            listContent.Insert(2, text);

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_Indicators_PSARBollinger_KiemTra.txt", listContent);
        }
        #endregion

        #region * Testing Stock_AVG_STD, Filter1
        public void Testing_Stock_AVG_STD(int soNgay, ref List<float> listAvg, ref List<float> listStd)
        {
            List<float> listResult = new List<float>();
            List<string> listcontent = new List<string>();
            List<float> listvalue = new List<float>();
            List<float> listTemp = new List<float>();
            listAvg = new List<float>();
            listStd = new List<float>();

            string first_date = "";
            float avg, std;
            foreach (CoPhieu cp in this.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    first_date = cp.DanhSachNgayGiaoDich_String[0];
                    break;
                }

            listcontent.Add("CP\tAvg\tStd");
            listcontent.Add("-----------------------");

            foreach (CoPhieu cp in this.DanhSachCoPhieu_List)
                if (cp.DanhSachNgayGiaoDich_String[0] == first_date)
                {
                    listvalue = new List<float>();
                    listTemp = cp.DanhSachGiaDongCua_DieuChinh;
                    for (int i = 0; i < listTemp.Count && i < soNgay; i++)
                        listvalue.Insert(0, (float)Math.Round(listTemp[i], 1));

                    List<float> DailyReturns = CoreFunctions.Tk_GetDailyReturn(listvalue);

                    avg = CoreFunctions.Tk_GetAverage(DailyReturns);
                    std = CoreFunctions.Tk_PopularStandardDeviation(DailyReturns);

                    avg = (float)Math.Round(avg, 5);
                    std = (float)Math.Round(std, 5);

                    listcontent.Add(cp.TenCoPhieu + "\t" + avg + "\t" + std);
                    listAvg.Add(avg);
                    listStd.Add(std);
                }
                else
                {
                    listcontent.Add(cp.TenCoPhieu + "\t" + -10000 + "\t" + -10000);
                    listAvg.Add(-10000);
                    listStd.Add(-10000);
                }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_stockAvgStd.txt", listcontent);
        }

        public List<float> Testing_Filter1(int soNgay = 20)
        {
            List<float> listResult = new List<float>();
            foreach (CoPhieu cp in _danhSachCoPhieu)
            {
                listResult.Add(Indicators.Filter1(cp.DanhSachGiaDongCua, soNgay));
            }
            return listResult;
        }
        #endregion

        #region * Testing Similar VNINDEX
        public List<float> Testing_TinhSimilarVNINDEX_Consine()
        {
            /// Tính Cosine Similar
            CoPhieu VNINDEX = new CoPhieu();
            foreach(CoPhieu cp in this._danhSachCoPhieu)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    VNINDEX = cp;
                    break;
                }
            List<float> listResult = new List<float>();
            float close, max, min,value;
            foreach (CoPhieu cp in this._danhSachCoPhieu)
            {
                close = CoreFunctions.MR_TinhCosineSimilar(cp.DanhSachGiaDongCua, VNINDEX.DanhSachGiaDongCua);
                max = CoreFunctions.MR_TinhCosineSimilar(cp.DanhSachGiaCaoNhat, VNINDEX.DanhSachGiaCaoNhat);
                min = CoreFunctions.MR_TinhCosineSimilar(cp.DanhSachGiaThapNhat, VNINDEX.DanhSachGiaThapNhat);

                value = (close + 0.5f * max + 0.5f * min) / 2f;
                value = (float)Math.Round(value, 3);
                listResult.Add(value);
            }
            return listResult;
        }

        public List<float> Testing_TinhSimilarVNINDEX_Euclid()
        {
            CoPhieu VNINDEX = new CoPhieu();
            foreach (CoPhieu cp in this._danhSachCoPhieu)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    VNINDEX = cp;
                    break;
                }
            List<float> listResult = new List<float>();
            float close, max, min, value;
            List<List<float>> listZscore = new List<List<float>>();
            listZscore.Add(CoreFunctions.Tk_GetZScores(VNINDEX.DanhSachGiaDongCua));
            listZscore.Add(CoreFunctions.Tk_GetZScores(VNINDEX.DanhSachGiaCaoNhat));
            listZscore.Add(CoreFunctions.Tk_GetZScores(VNINDEX.DanhSachGiaThapNhat));

            foreach (CoPhieu cp in this._danhSachCoPhieu)
            {
                close = CoreFunctions.MR_TinhEuclidSimilar(CoreFunctions.Tk_GetZScores(cp.DanhSachGiaDongCua), listZscore[0]);
                max = CoreFunctions.MR_TinhEuclidSimilar(CoreFunctions.Tk_GetZScores(cp.DanhSachGiaCaoNhat), listZscore[1]);
                min = CoreFunctions.MR_TinhEuclidSimilar(CoreFunctions.Tk_GetZScores(cp.DanhSachGiaThapNhat), listZscore[2]);

                value = (close +  max + min) / 3f;
                value = (float)Math.Round(value, 3);
                listResult.Add(value);
            }
            return listResult;
        }
        #endregion

        #region * Tesing Dao Động Giá
        public List<List<float>> Testing_DaoDongGia()
        {
            List<List<float>> result = new List<List<float>>();
            List<float> valAddList = new List<float>();
            List<int> listCount = new List<int>();
             List<float> listVal = new List<float>();
            int count;
            float chechlech;
            foreach (CoPhieu cp in this._danhSachCoPhieu)
            {
                listVal = cp.DanhSachGiaDongCua_DieuChinh;
                listCount = new List<int>();
                valAddList = new List<float>();
                count = 0;

                for (int i = 0; i < 4; i++)
                    listCount.Add(0);

                for (int i = 1; i < listVal.Count; i++)
                {
                    chechlech = (float)(listVal[i - 1] - listVal[i]) / listVal[i];
                    chechlech = (float)Math.Abs(chechlech);
                    count++;

                    if (chechlech <= 0.01f)
                        listCount[0]++;
                    else if (chechlech <= 0.03f)
                        listCount[1]++;
                    else if (chechlech <= 0.05f)
                        listCount[2]++;
                    else
                        listCount[3]++;
                }

                for (int i = 0; i < listCount.Count; i++)
                {
                    chechlech = (float)listCount[i] / count;
                    chechlech = (float)Math.Round(chechlech, 2);
                    valAddList.Add(chechlech);
                }
                result.Add(valAddList);
            }
            return result;
        }
        #endregion

        #region * Tesing Hiện Tượng Giá
        public void Testing_HienTuong_XanhVoDoLong(ref List<float> XanhVoDoLong, ref List<float> DoVoXanhLong
            , float tile = 0.8f, float valMin = 450f)
        {
            List<float> listGiaVNINDEX = new List<float>();
            foreach (CoPhieu cp in _danhSachCoPhieu)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    listGiaVNINDEX = cp.DanhSachGiaDongCua;
                    break;
                }

            int countTang, count, countGiam;
            float chechlech, chechlechVNINDEX;
            List<float> listGiaCP = new List<float>();
            for (int i = 1; i < listGiaVNINDEX.Count; i++)
            {
                if (i > 500)
                {
                    XanhVoDoLong.Add(valMin);
                    DoVoXanhLong.Add(valMin);
                    continue;
                }

                count = 0; countTang = 0; countGiam = 0;
                chechlechVNINDEX = (listGiaVNINDEX[i - 1] - listGiaVNINDEX[i]) / listGiaVNINDEX[i];
                foreach (CoPhieu cp in _danhSachCoPhieu)
                {
                    listGiaCP = cp.DanhSachGiaDongCua;
                    if (listGiaCP.Count > i && cp.TenCoPhieu != "^VNINDEX")
                    {
                        chechlech = (listGiaCP[i - 1] - listGiaCP[i]) / listGiaCP[i];

                        if (chechlech != 0)
                            count++;

                        if (chechlech > 0)
                            countTang++;
                        else if (chechlech < 0)
                            countGiam++;
                    }
                }

                if ((float)countTang / count > tile && chechlechVNINDEX < 0)
                    DoVoXanhLong.Add(listGiaVNINDEX[i]);
                else
                    DoVoXanhLong.Add(valMin);

                if ((float)countGiam / count > tile && chechlechVNINDEX > 0)
                    XanhVoDoLong.Add(listGiaVNINDEX[i]);
                else
                    XanhVoDoLong.Add(valMin);
            }
        }

        public void Testing_HienTuongGia(ref float maxChechlechTang, ref float maxChechlechGiam)
        {
            List<float> listGiaVNINDEX = new List<float>();
            
          
            foreach (CoPhieu cp in _danhSachCoPhieu)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    listGiaVNINDEX = cp.DanhSachGiaDongCua;
                    break;
                }

            int countTang, count, countGiam;
            float chechlech, chechlechVNINDEX, chechlechTang, chechlechGiam;
            maxChechlechTang = 0f; maxChechlechGiam = 0f;

            List<float> listGiaCP = new List<float>();
            for (int i = 1; i < listGiaVNINDEX.Count && i < 500; i++)
            {
                count = 0; countTang = 0; countGiam = 0;
                chechlechVNINDEX = (listGiaVNINDEX[i - 1] - listGiaVNINDEX[i]) / listGiaVNINDEX[i];
                foreach (CoPhieu cp in _danhSachCoPhieu)
                {
                    listGiaCP = cp.DanhSachGiaDongCua;
                    if (listGiaCP.Count > i && cp.TenCoPhieu != "^VNINDEX")
                    {
                        chechlech = (listGiaCP[i - 1] - listGiaCP[i]) / listGiaCP[i];

                        if (chechlech != 0)
                            count++;

                        if (chechlech > 0)
                            countTang++;
                        else if (chechlech < 0)
                            countGiam++;
                    }
                }

                chechlechTang = (float)countTang / count;
                chechlechGiam = (float)countGiam / count;

                if (chechlechVNINDEX < 0 && chechlechTang > maxChechlechTang)
                    maxChechlechTang = chechlechTang;

                if (chechlechVNINDEX > 0 && chechlechGiam > maxChechlechGiam)
                    maxChechlechGiam = chechlechGiam;              
            }


        }
        #endregion

        #region * Tesing RSI toàn bộ các CP
        public void Testing_RSI_TatCaCacCP()
        {
            int count_morethan70 = 0, count_lessthan30 = 0, count_05 = 0, count_other = 0, sum;
            float score;
            string str = "";
            List<string> listNgayGiaoDich = new List<string>();     
            List<string> listFile = new List<string>();
            List<float> listTemp = new List<float>();
            foreach (CoPhieu cp in _danhSachCoPhieu)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    listNgayGiaoDich = cp.DanhSachNgayGiaoDich_String;
                    break;
                }

            count_morethan70 = 0; count_lessthan30 = 0; count_05 = 0; count_other = 0;
            foreach (CoPhieu cp in _danhSachCoPhieu)
            {
                if (!cp.DanhSachNgayGiaoDich_String.Contains(listNgayGiaoDich[0])
                    || !cp.DanhSachNgayGiaoDich_String.Contains(listNgayGiaoDich[15]))
                    continue;

                if (cp.DanhSachNgayGiaoDich.Count > 100)
                {

                    score = cp.TinhDanhSachChiSo_RelativeStrengIndex_RSI(14);
                    if (score >= 70f) count_morethan70++;
                    else if (score >= 50f) count_05++;
                    else if (score <= 30f) count_lessthan30++;
                    else count_other++;
                }
            }

            sum = count_morethan70 + count_05 + count_lessthan30 + count_other;
          
            listTemp.Add((float)Math.Round((float)count_morethan70 / sum * 100, 0));
            listTemp.Add((float)Math.Round((float)count_05 / sum * 100, 0));
            listTemp.Add((float)Math.Round((float)count_lessthan30 / sum * 100, 0));
            listTemp.Add((float)Math.Round((float)count_other / sum * 100, 0));

            listFile = CoreFunctions.File_LoadAnyFile(CoreFunctions._pathHOSE_HNX + @"\Testing_RSI.txt");
            listFile.RemoveAt(0);
            listFile.RemoveAt(0);
            str = listNgayGiaoDich[0] + "\t";
            foreach (float t in listTemp)
                str += t.ToString() + "\t";
            listFile.Insert(0, str);
            listFile.Insert(0, "CP\t\t>70%\t>50%\t>30%\tOther");
            listFile.Insert(1, "-------------------------------------------------------");

            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "Testing_RSI.txt", listFile);
        }
        #endregion

        #region * Tesing Excel
        public void Testing_Excel()
        {
            #region **************** Biến - Khai báo ban đầu
            List<string> listStr = new List<string>();
            List<float> listGia = new List<float>();
            List<float> listValue1 = new List<float>();
            List<float> listValue2 = new List<float>();
            List<float> listValue3 = new List<float>();
            List<bool> listBool = new List<bool>();
            List<bool> listBool1 = new List<bool>();
            char c = 'A';
            int count = 0, row, col, symbol = c;
            listStr = DanhSachTenCoPhieu;
            count = DanhSachTenCoPhieu.Count;
            this.File_CapNhatMaNganh();

            List<List<float>> listListValues = new List<List<float>>();
            List<List<float>> listDaoDongGia = Testing_DaoDongGia();
            listValue1 = new List<float>();
            listValue2 = new List<float>();
            List<float> listTemp = new List<float>();

            #endregion

            #region Tính toán trước khi ghi vào file
           
            #region Average, Std, Reward 60 ngày, 3 ngày
            Testing_Stock_AVG_STD(60, ref listValue1, ref listValue2);
            listListValues.Add(listValue1.GetRange(0, count)); /// index = 0
            listListValues.Add(listValue2.GetRange(0, count)); /// index = 1

            for (int i = 0; i < count; i++)
                listTemp.Add(listValue1[i] / listValue2[i]);
            listListValues.Add(listTemp); /// index = 2
                                          
            Testing_Stock_AVG_STD(4, ref listValue1, ref listValue2);
            List<float> listReward3Ngay = new List<float>();
            List<float> listReward8Ngay = new List<float>();
            for (int i = 0; i < count; i++)
                listReward3Ngay.Add(listValue1[i] / listValue2[i]);

            Testing_Stock_AVG_STD(8, ref listValue1, ref listValue2);
            for (int i = 0; i < count; i++)
                listReward8Ngay.Add(listValue1[i] / listValue2[i]);
            #endregion

            #region MFI, RSI, IMI
            listValue1 = Testing_MFI_MoneyFlowIndex(14);
            listValue2 = Testing_RSI_RelativeStrengIndex(20);
            listValue3 = Testing_IMI_IntradayMomentumIndex(14);

            listListValues.Add(listValue1.GetRange(0, count)); /// index = 3
            listListValues.Add(listValue2.GetRange(0, count)); /// index = 4
            listListValues.Add(listValue3.GetRange(0, count)); /// index = 5
            List<int> listAvg_MFI_RSI_IMI = new List<int>();
            for (int i = 0; i < listListValues[3].Count; i++)
            {
                listAvg_MFI_RSI_IMI.Add(
                    (int)(listListValues[3][i] + listListValues[4][i] + listListValues[5][i])/3
                    );
            }

            List<int> soNgayCachDinhGanNhat_AvgMFI_RSI_IMI = new List<int>();
            List<int> soDinhHistogram_AVG = new List<int>();
            ShareData.Get_CoPhieu(this.DanhSachTenCoPhieu).
            Testing_AvgRSIMFIIMI_Statistic_TinHieuMua(9, 1, 4, ref soNgayCachDinhGanNhat_AvgMFI_RSI_IMI, ref soDinhHistogram_AVG);
            
            #endregion

            #region PSAR
            Testing_PSAR(5, ref listValue1, ref listValue2);
            listListValues.Add(listValue1.GetRange(0, count)); /// index = 6
            listListValues.Add(listValue2.GetRange(0, count)); /// index = 7
            #endregion

            #region BB && Volatity && cosine similar VNINDEX
            listValue1 = Testing_BollingerBand(20, ref listValue2);
            listListValues.Add(listValue1.GetRange(0, count)); /// index = 8
            listListValues.Add(listValue2.GetRange(0, count)); /// index = 9
            /// 
            Testing_TinhVolatility(ref listValue1, ref listValue2);
            listListValues.Add(listValue1.GetRange(0, count)); /// index = 10
            listListValues.Add(listValue2.GetRange(0, count)); /// index = 11

            listValue1 = Testing_TinhSimilarVNINDEX_Consine();
            listValue2 = Testing_TinhSimilarVNINDEX_Euclid();
            listListValues.Add(listValue1.GetRange(0, count)); /// index = 12
            listListValues.Add(listValue2.GetRange(0, count)); /// index = 13

            ///Reward volality / std
            listValue1 = new List<float>();
            for (int i = 0; i < listListValues[10].Count; i++)
                listValue1.Add((float)Math.Round(listListValues[10][i] / listListValues[1][i], 4));
            listListValues.Add(listValue1); /// index = 14;
            #endregion

            #region MACD DEMA-TEMA - histogram
            List<int> listSignalHistogram = new List<int>();
            List<int> listSoTinHieuMua = new List<int>();
            //ShareData.Get_CoPhieu(this.DanhSachTenCoPhieu).
                Testing_MACD_TinHieuMua(9, 1, 4, ref listBool, ref listBool1, ref listSignalHistogram
                , ref listSoTinHieuMua);
            #endregion

            #region Filter 1
            List<float> listFilter = Testing_Filter1(20);
            #endregion

            #region Tính số ngày cách Cross EMA 13, 34
            List<int> listCrossEMA = Testing_SoNgayCachCrossEMA(25, 45);
            #endregion

            #region Tính HubScore
            List<float> HubScore = Testing_TinhHubScore(1,4,0.7f);
            #endregion

            #endregion

            #region Mở cổng COM ghi File EXCEL
            ExcelCOM.Application exApp = new ExcelCOM.Application();
            ExcelCOM.Workbook exBook = exApp.Workbooks.Add(ExcelCOM.XlWBATemplate.xlWBATWorksheet);
            ExcelCOM.Worksheet exSheet = (ExcelCOM.Worksheet)exBook.Worksheets[1];

            exSheet.Name = "Testing";

            ExcelCOM.Range r;

            #endregion

            #region Fill Field

            #region **************** Fill Tên CP & Giá đóng cửa & Khối lượng 10 ngày
            row = 2; col = 1;

            exSheet.Cells[row, col] = "Tên CP";
            exSheet.Cells[row, col + 1] = "Mã Ngành";
            exSheet.Cells[row, col + 2] = "Giá đóng cửa";
            exSheet.Cells[row, col + 3] = "KL Trung bình 10 ngày (k)";
            exSheet.Cells[row, col + 4] = "% Thay đổi KL TB";
            exSheet.Cells[row, col + 5] = "Giá trị TB 10 ngày (tỷ)";

            row++;

            for (int i = 0; i < count; i++)
            {
                exSheet.Cells[row, col] = DanhSachTenCoPhieu[i];
                exSheet.Cells[row, col + 1] = this._danhSachCoPhieu[i].MaNganh;
                exSheet.Cells[row, col + 2] = Math.Round(_danhSachCoPhieu[i].DanhSachGiaDongCua[0], 2);
                exSheet.Cells[row, col + 3] = ((float)Math.Round(_danhSachCoPhieu[i].KhoiLuongTB10Ngay / 1000, 1)).ToString();
                exSheet.Cells[row, col + 4] = ((float)Math.Round(_danhSachCoPhieu[i].ThayDoiKhoiLuongTheoNgay, 1)).ToString();
                exSheet.Cells[row, col + 5] = ((float)Math.Round(_danhSachCoPhieu[i].GiaTriGiaoDich10Ngay / 1000000f, 1)).ToString();
                row++;
            }
            col += 6;
            #endregion

            #region **************** Fill Average, Std, Reward  60 ngày
            row = 2;
            exSheet.Cells[row, col] = "Avg60";
            exSheet.Cells[row, col + 1] = "Std60";
            exSheet.Cells[row, col + 2] = "Reward/Risk60";
            exSheet.Cells[row, col + 3] = "Reward/Risk3";
            exSheet.Cells[row, col + 4] = "Reward/Risk8";
            row++;

            for (int i = 0; i < count; i++)
            {
                exSheet.Cells[row, col] = Math.Round(listListValues[0][i], 5);
                exSheet.Cells[row, col + 1] = Math.Round(listListValues[1][i], 5);
                exSheet.Cells[row, col + 2] = Math.Round(listListValues[2][i], 3);
                exSheet.Cells[row, col + 3] = Math.Round(listReward3Ngay[i], 3);
                exSheet.Cells[row, col + 4] = Math.Round(listReward8Ngay[i], 3);
                row++;
            }
            col += 5;
            #endregion

            #region **************** Fill MFI, RSI, IMI
            row = 2;
            exSheet.Cells[row, col] = "MFI";
            exSheet.Cells[row, col + 1] = "RSI";
            exSheet.Cells[row, col + 2] = "IMI";
            exSheet.Cells[row, col + 3] = "AVG_MFI_RSI_IMI";
           
            row++;

            for (int i = 0; i < count; i++)
            {
                exSheet.Cells[row, col] = Math.Round(listListValues[3][i], 2);
                if (listListValues[3][i] <= 20)
                {
                    r = (ExcelCOM.Range)exSheet.Cells[row, col];
                    r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                }

                exSheet.Cells[row, col + 1] = listListValues[4][i];
                if (listListValues[4][i] <= 30)
                {
                    r = (ExcelCOM.Range)exSheet.Cells[row, col + 1];
                    r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                }

                exSheet.Cells[row, col + 2] = listListValues[5][i];
                if (listListValues[5][i] <= 30)
                {
                    r = (ExcelCOM.Range)exSheet.Cells[row, col + 2];
                    r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                }

                exSheet.Cells[row, col + 3] = listAvg_MFI_RSI_IMI[i];
                if (listAvg_MFI_RSI_IMI[i] <= 30)
                {
                    r = (ExcelCOM.Range)exSheet.Cells[row, col + 3];
                    r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                }
                row++;
            }
            col += 4;
            #endregion

            #region **************** Fill PSAR
            row = 1;
            c = 'A';
            c = (char)((int)c + col - 1);

            exSheet.get_Range(c + row.ToString(), (char)((int)c + 1) + row.ToString()).Merge(false);
            r = (ExcelCOM.Range)exSheet.get_Range(c + row.ToString(), (char)((int)c + 1) + row.ToString());
            r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
            r.FormulaR1C1 = "PSAR";
            row++;

            exSheet.Cells[row, col] = "AFD0";
            exSheet.Cells[row, col + 1] = "AFD1";

            row++;

            for (int i = 0; i < count; i++)
            {
                exSheet.Cells[row, col] = Math.Round(listListValues[6][i], 2);
                exSheet.Cells[row, col + 1] = Math.Round(listListValues[7][i], 2);
                if (_danhSachCoPhieu[i].DanhSachGiaDongCua[0] >= listListValues[6][i]
                    && _danhSachCoPhieu[i].DanhSachGiaDongCua[0] <= listListValues[7][i])
                {
                    r = (ExcelCOM.Range)exSheet.Cells[row, col];
                    r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                    r = (ExcelCOM.Range)exSheet.Cells[row, col + 1];
                    r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                }
                row++;
            }
            col += 2;
            #endregion

            #region **************** Fill MACD DEMA - TEMA - histogram
            row = 1;
            c = 'A';
            c = (char)((int)c + col - 1);

            exSheet.get_Range(c + row.ToString(), (char)((int)c + 2) + row.ToString()).Merge(false);
            r = (ExcelCOM.Range)exSheet.get_Range(c + row.ToString(), (char)((int)c + 2) + row.ToString());
            r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue);
            r.FormulaR1C1 = "MACD";
            row++;

            exSheet.Cells[row, col] = "DEMA";
            exSheet.Cells[row, col + 1] = "TEMA";
            exSheet.Cells[row, col + 2] = "Histogram MACD Am";
            exSheet.Cells[row, col + 3] = "CrosEMA13_34";
            exSheet.Cells[row, col + 4] = "Histogram AVG_MFI_RSI_IMI";
            row++;

            for (int i = 0; i < count; i++)
            {
                if (listBool[i])
                {
                    exSheet.Cells[row, col] = "X";
                    r = (ExcelCOM.Range)exSheet.Cells[row, col];
                    r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                }
                if (listBool1[i])
                {
                    exSheet.Cells[row, col + 1] = "X";
                    r = (ExcelCOM.Range)exSheet.Cells[row, col + 1];
                    r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                }

                exSheet.Cells[row, col + 2] = listSignalHistogram[i];
                r = (ExcelCOM.Range)exSheet.Cells[row, col + 2];
                if (listSoTinHieuMua[i] == 2)
                    r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                else if(listSoTinHieuMua[i] > 2)
                    r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue);

                exSheet.Cells[row, col + 3] = listCrossEMA[i];

                exSheet.Cells[row, col + 4] = soNgayCachDinhGanNhat_AvgMFI_RSI_IMI[i];
                if (soNgayCachDinhGanNhat_AvgMFI_RSI_IMI[i] >= 0 && soNgayCachDinhGanNhat_AvgMFI_RSI_IMI[i] != 9999)
                {
                    if (soDinhHistogram_AVG[i] == 2)
                    {
                        r = (ExcelCOM.Range)exSheet.Cells[row, col + 4];
                        r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue);
                    }
                    else if (soDinhHistogram_AVG[i] == 1)
                    {
                        r = (ExcelCOM.Range)exSheet.Cells[row, col + 4];
                        r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                    }
                }

                row++;
            }
            col += 5;
            #endregion

            #region **************** Fill Bollingerband
            row = 1;
            c = 'A';
            c = (char)((int)c + col - 1);

            exSheet.get_Range(c + row.ToString(), (char)((int)c + 1) + row.ToString()).Merge(false);
            r = (ExcelCOM.Range)exSheet.get_Range(c + row.ToString(), (char)((int)c + 1) + row.ToString());
            r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
            r.FormulaR1C1 = "Bollinger";
            row++;

            exSheet.Cells[row, col] = "%Giá-Đường dưới";
            exSheet.Cells[row, col + 1] = "%Trên-Dưới";
            row++;

            for (int i = 0; i < count; i++)
            {
                exSheet.Cells[row, col] = Math.Round(listListValues[8][i], 2);
                if (listListValues[8][i] <= 0)
                {
                    r = (ExcelCOM.Range)exSheet.Cells[row, col];
                    r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                }
                
                exSheet.Cells[row, col + 1] = Math.Round(listListValues[9][i], 2); 
                row++;
            }
            col += 2;
            #endregion

            #region **************** Fill Volality
            row = 2;
            exSheet.Cells[row, col] = "Volality";
            exSheet.Cells[row, col + 1] = "Beta Volality";
            exSheet.Cells[row, col + 2] = "Reward Volality";
            row++;

            for (int i = 0; i < count; i++)
            {
                exSheet.Cells[row, col] = Math.Round(listListValues[10][i], 2);
                exSheet.Cells[row, col + 1] = Math.Round(listListValues[11][i], 2);
                exSheet.Cells[row, col + 2] = Math.Round(listListValues[14][i], 2);
                row++;
            }
            col += 3;
            #endregion

            #region **************** Fill Cosine Similar VNINDEX
            row = 2;
            exSheet.Cells[row, col] = "Cosine vnindex";
            row++;

            for (int i = 0; i < count; i++)
            {
                exSheet.Cells[row, col] = Math.Round(listListValues[12][i], 2);
                row++;
            }
            col += 1;
            #endregion

            #region **************** Fill Euclid Similar VNINDEX
            row = 2;
            exSheet.Cells[row, col] = "Euclid vnindex";
            row++;

            for (int i = 0; i < count; i++)
            {
                exSheet.Cells[row, col] = (float)Math.Round(listListValues[13][i], 2);
                row++;
            }
            col += 1;
            #endregion

            #region **************** Fill Hub - Authority - PageRank
            row = 2;
            exSheet.Cells[row, col] = "Hub Giá";
            //exSheet.Cells[row, col + 1] = "Authority Giá";
            //exSheet.Cells[row, col + 2] = "PageRank Giá";          
            row++;
            ////List<List<float>> listList = Testing_TinhHubAuthorityPageRank_Delay_Gia_KhoiLuong(6, 0.9f, 60, 30);
            //List<List<float>> listList = Testing_TinhHubAuthorityPageRank_Delay_Gia(6, 0.9f, 60, 30);
            for (int i = 0; i < count; i++)
            {
                  exSheet.Cells[row, col] = Math.Round(HubScore[i], 2);
            //    exSheet.Cells[row, col + 1] = Math.Round(listList[1][i],3);
            //    exSheet.Cells[row, col + 2] = Math.Round(listList[2][i],3);
                  row++;
            }
            col += 1;
            #endregion

            #region **************** Fill Filter 1 (sức mạnh trong ngắn hạn)
            row = 2;
            exSheet.Cells[row, col] = "Filter1";
            row++;
            for (int i = 0; i < count; i++)
            {
                exSheet.Cells[row, col] = listFilter[i];
                row++;
            }
            col += 1;
            #endregion

            #region **************** Fill T cộng
            List<int> listIntValue = new List<int>();
            listIntValue.AddRange(new int[] { 8, 30, 60 });
            List<List<float>> listTCong = Testing_TinhT_Cong(listIntValue);

            row = 1;
            //c = 'A';
            //c = (char)((int)c + col - 1);
            //exSheet.get_Range(c + row.ToString(), (char)((int)c + listTCong.Count - 1) + row.ToString()).Merge(false);
            //r = (ExcelCOM.Range)exSheet.get_Range(c + row.ToString(), (char)((int)c + listTCong.Count - 1) + row.ToString());
            //r.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
            //r.FormulaR1C1 = "T cộng T+";
            row++;

            for (int i = 0; i < listIntValue.Count; i++)
                exSheet.Cells[row, col + i] = "%T + " + listIntValue[i].ToString();
            row++;

            for (int i = 0; i < count; i++)
            {
                for (int j = 0; j < listIntValue.Count; j++)
                    exSheet.Cells[row, col + j] = listTCong[j][i];
                row++;
            }
            col += listIntValue.Count;
            #endregion

            #region **************** Fill Cluster Giá
            //List<List<string>> listCluster = Testing_MarkovCluster(1, 0.93f);
            //row = 2;
            //exSheet.Cells[row, col] = "Cluster Giá";
            //row++;
            //Testing_TinhVolatility(ref listValue1, ref listValue2);
            //for (int i = 0; i < count; i++)
            //{
            //    str = DanhSachTenCoPhieu[i];
            //    for (int k = 0; k < listCluster.Count; k++)
            //        for (int j = 0; j < listCluster[k].Count; j++)
            //            if (listCluster[k][j].Contains(str))
            //            {
            //                exSheet.Cells[row, col] = (k + 1);
            //                k = listCluster.Count;
            //                break;
            //            }
            //    row++;
            //}
            //col++;
            #endregion

            #region **************** Ranking Hub - Authority - PageRank - Total - Z score
            //row = 2;
            //exSheet.Cells[row, col] = "Hub";
            //exSheet.Cells[row, col + 1] = "Authority";
            //exSheet.Cells[row, col + 2] = "PageRank";
            //exSheet.Cells[row, col + 3] = "Total Ranking";
            //exSheet.Cells[row, col + 4] = "Z-Score";
            //int max = count + 3;

            //List<List<float>> listList_Zscore = new List<List<float>>();
            //List<float> list_Zscore = new List<float>();
            //for (int i = 0; i < 3; i++)
            //    listList_Zscore.Add(CoreFunctions.Tk_GetZScores(listList[i]));
            //for (int i = 0; i < count; i++)
            //    list_Zscore.Add((float)Math.Round(listList_Zscore[0][i] + listList_Zscore[1][i] + listList_Zscore[2][i], 3));

            //for (int i = 0; i < count; i++)
            //{
            //    exSheet.Cells[row + i + 1, col] = "=RANK(N" + (row + i + 1) + ",$N$3:$N$" + max + ",0)";
            //    exSheet.Cells[row + i + 1, col + 1] = "=RANK(O" + (row + i + 1) + ",$O$3:$O$" + max + ",0)";
            //    exSheet.Cells[row + i + 1, col + 2] = "=RANK(P" + (row + i + 1) + ",$P$3:$P$" + max + ",0)";
            //    exSheet.Cells[row + i + 1, col + 3] = "=SUM(U" + (row + i + 1) + ":W" + (row + i + 1) + ")";
            //    exSheet.Cells[row + i + 1, col + 4] = Math.Round(list_Zscore[i], 3);

            //}
            //col += 5;

            //List<string> listContent = CoreFunctions.File_LoadAnyFile(CoreFunctions._pathHOSE_HNX + @"\Testing_HubAuthorityPageRankToanBo_Delay.txt");
            //if (listContent.Count == 0 || listContent[1].Contains(CoreFunctions._ngayBatDau) == false)
            //{
            //    if (listContent.Count != 0)
            //        listContent.RemoveAt(0);

            //    string text = "";
            //    List<string> listphu = new List<string>();
            //    for (int i = 0; i < this._danhSachCoPhieu.Count; i++)
            //    {
            //        text = this._danhSachCoPhieu[i].TenCoPhieu + "\t"
            //            + CoreFunctions._ngayBatDau + "\t"
            //            + Math.Round(listList[0][i], 2).ToString() + "\t"
            //            + Math.Round(listList[1][i], 2).ToString() + "\t"
            //            + Math.Round(listList[2][i], 2).ToString() + "\t"
            //            + Math.Round(list_Zscore[i], 2).ToString();
            //        listphu.Add(text);
            //    }

            //    listphu.AddRange(listContent);

            //    listphu.Insert(0, "CP\tNgayGD\tHub\tAuth\tPage\tZscore");

            //    text = "Testing_HubAuthorityPageRankToanBo_Delay.txt";

            //    CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, text, listphu);
            //}
            #endregion

            #region **************** Fill Dao động giá
            row = 2;
            exSheet.Cells[row, col] = "<= 1%";
            exSheet.Cells[row, col + 1] = "<= 3%";
            exSheet.Cells[row, col + 2] = "<= 5%";
            exSheet.Cells[row, col + 3] = "> 5%";
            row++;
            for (int i = 0; i < count; i++)
            {
                for (int j = 0; j < listDaoDongGia[i].Count; j++)
                    exSheet.Cells[row, col + j] = listDaoDongGia[i][j];
                row++;
            }
            col += 4;
            #endregion

            #endregion

            #region **************** Tạo File Excel
            string path = CoreFunctions._pathHOSE_HNX + @"Excel\Testing_Excel_" + CoreFunctions._ngayBatDau + ".xls";
            exApp.Visible = false;
            exBook.SaveAs(path, ExcelCOM.XlFileFormat.xlWorkbookNormal,
                null, null, false, false,
                ExcelCOM.XlSaveAsAccessMode.xlExclusive,
                false, false, false, false, false);

            exBook.Close(false, false, false);
            exApp.Quit();

            System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp);
            #endregion
        }
        #endregion

        #region * Tesing Portfolio
        public void Testing_Portfolio_MyPortfolio()
        {
            List<string> listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_MyPortfolioTest.txt");

            string[] part = listFile[0].Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries); ;
            string dateBegin = part[0], dateEnd = part[1];

            listFile = CoreFunctions.File_LoadAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_MaxAllocationPortfolio.txt");
            List<string> listNameCP = new List<string>();
            List<float> listPercent = new List<float>();
            foreach (string item in listFile)
            {
                part = item.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                listNameCP.Add(part[0]);
                listPercent.Add(float.Parse(part[1]));
            }

            float value = this.Xuly_TangTruongGia(listNameCP, listPercent, dateEnd, dateBegin);
            listFile = new List<string>();
            listFile.Add(dateBegin + "\t" + dateEnd);
            listFile.Add("Value: " + value);

            foreach (CoPhieu vnindex in this.DanhSachCoPhieu_List)
                if (vnindex.TenCoPhieu == "^VNINDEX")
                {
                    listFile.Add("Value vnindex: " + vnindex.Xuly_TangTruongGiaDongCua(dateEnd, dateBegin));
                    break;
                }

            listFile.Add("Portfolio:");
            for (int i = 0; i < listNameCP.Count; i++)
                listFile.Add(listNameCP[i] + ":" + listPercent[i]);

            CoreFunctions.File_WriteAnyFile(System.Windows.Forms.Application.StartupPath
                + @"\HOSE\BackTest_MyPortfolioTest.txt", listFile);
        }

        public void Testing_Portfolio_ConvexOptimation_Volality(List<string> nameStockPortfolio
                                   , int soNgay, ref List<float> listVolality, ref List<float> listStd)
        {
            List<string> listcontent = new List<string>();
            List<string> listStock = new List<string>();

            List<float> listResult = new List<float>();
            List<float> listvalue = new List<float>();
            List<float> listTemp = new List<float>();

            List<List<float>> listPriceOfStock = new List<List<float>>();
            listVolality = new List<float>();
            listStd = new List<float>();

            string first_date = "";
            float volality, std;
            foreach (CoPhieu cp in this.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    first_date = cp.DanhSachNgayGiaoDich_String[0];
                    break;
                }

            listcontent.Add("CP\tVol\tStd");
            listcontent.Add("-----------------------");
            int count = 0;
            foreach (CoPhieu cp in this.DanhSachCoPhieu_List)
                if (cp.DanhSachNgayGiaoDich_String[0] == first_date && nameStockPortfolio.Contains(cp.TenCoPhieu))
                {
                    listvalue = new List<float>();
                    listTemp = cp.DanhSachGiaDongCua_DieuChinh;
                    for (int i = 0; i < listTemp.Count && i < soNgay; i++)
                        listvalue.Add(listTemp[i]);

                    if (count < 200) /// số lượng cổ phiếu
                    {
                        count++;
                        listPriceOfStock.Add(new List<float>());
                        foreach (float val in listvalue)
                            listPriceOfStock[listPriceOfStock.Count - 1].Add((float)Math.Round(val, 1));

                        listPriceOfStock[listPriceOfStock.Count - 1] = CoreFunctions.Xuly_DaoNguocList(listPriceOfStock[listPriceOfStock.Count - 1]);
                        List<float> DailyReturns = CoreFunctions.Tk_GetDailyReturn(listPriceOfStock[listPriceOfStock.Count - 1]);
                        volality = cp.TinhVolality();
                        std = CoreFunctions.Tk_PopularStandardDeviation(DailyReturns);

                        listVolality.Add(volality);
                        listStd.Add(std);
                        listStock.Add(cp.TenCoPhieu);
                        std = (float)Math.Round(std, 6);
                        listcontent.Add(cp.TenCoPhieu + "\t" + volality + "\t" + std);
                    }
                }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_stockAvgStd.txt", listcontent);

            listcontent = new List<string>();
            string row = "";
            foreach (string name in listStock)
                row += name + ",";
            row = row.Substring(0, row.Length - 1);
            listcontent.Add(row);
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_NameStock.txt", listcontent);

            listcontent = new List<string>();
            row = "";
            int length = listPriceOfStock[0].Count;
            for (int i = 0; i < length; i++)
            {
                row = "";
                foreach (List<float> list in listPriceOfStock)
                    row += (float)Math.Round(list[i], 1) + ",";
                row = row.Substring(0, row.Length - 1);
                listcontent.Add(row);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_PriceStock.txt", listcontent);
        }

        public void Testing_BackTest_Stock_ConvexOptimation(List<string> nameStockPortfolio
                                   , int soNgay, ref List<float> listAvg, ref List<float> listStd)
        {
            List<string> listcontent = new List<string>();
            List<string> listStock = new List<string>();

            List<float> listResult = new List<float>();
            List<float> listvalue = new List<float>();
            List<float> listTemp = new List<float>();

            List<List<float>> listPriceOfStock = new List<List<float>>();
            listAvg = new List<float>();
            listStd = new List<float>();

            string first_date = "";
            float avg, std;
            foreach (CoPhieu cp in this.DanhSachCoPhieu_List)
                if (cp.TenCoPhieu == "^VNINDEX")
                {
                    first_date = cp.DanhSachNgayGiaoDich_String[0];
                    break;
                }

            listcontent.Add("CP\tAvg\tStd");
            listcontent.Add("-----------------------");
            int count = 0;
            foreach (CoPhieu cp in this.DanhSachCoPhieu_List)
                if (cp.DanhSachNgayGiaoDich_String[0] == first_date && nameStockPortfolio.Contains(cp.TenCoPhieu))
                {
                    listvalue = new List<float>();
                    listTemp = cp.DanhSachGiaDongCua_DieuChinh;
                    for (int i = 0; i < listTemp.Count && i < soNgay; i++)
                        listvalue.Add(listTemp[i]);

                    if (count < 200) /// số lượng cổ phiếu
                    {
                        count++;
                        listPriceOfStock.Add(new List<float>());
                        foreach (float val in listvalue)
                            listPriceOfStock[listPriceOfStock.Count - 1].Add((float)Math.Round(val, 1));

                        listPriceOfStock[listPriceOfStock.Count - 1] = CoreFunctions.Xuly_DaoNguocList(listPriceOfStock[listPriceOfStock.Count - 1]);
                        List<float> DailyReturns = CoreFunctions.Tk_GetDailyReturn(listPriceOfStock[listPriceOfStock.Count - 1]);
                        avg = CoreFunctions.Tk_GetAverage(DailyReturns);
                        std = CoreFunctions.Tk_PopularStandardDeviation(DailyReturns);

                        listAvg.Add(avg);
                        listStd.Add(std);
                        listStock.Add(cp.TenCoPhieu);
                        avg = (float)Math.Round(avg, 6);
                        std = (float)Math.Round(std, 6);
                        listcontent.Add(cp.TenCoPhieu + "\t" + avg + "\t" + std);
                    }
                }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_stockAvgStd.txt", listcontent);

            listcontent = new List<string>();
            string row = "";
            foreach (string name in listStock)
                row += name + ",";
            row = row.Substring(0, row.Length - 1);
            listcontent.Add(row);
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_NameStock.txt", listcontent);

            listcontent = new List<string>();
            row = "";
            int length = listPriceOfStock[0].Count;
            for (int i = 0; i < length; i++)
            {
                row = "";
                foreach (List<float> list in listPriceOfStock)
                    row += (float)Math.Round(list[i], 1) + ",";
                row = row.Substring(0, row.Length - 1);
                listcontent.Add(row);
            }
            CoreFunctions.File_WriteAnyFile(CoreFunctions._pathHOSE_HNX, "BackTest_OptPort_PriceStock.txt", listcontent);
        }
        #endregion

        #endregion

        #endregion

        #region ------ Properties ------
        public List<CoPhieu> DanhSachCoPhieu_List
        {
            get { return _danhSachCoPhieu; }
        }

        public List<string> DanhSachTenCoPhieu
        {
            get
            {
                List<string> result = new List<string>();
                foreach (CoPhieu cp in _danhSachCoPhieu)
                    result.Add(cp.TenCoPhieu);
                return result;
            }
        }

        public string HeaderFile
        {
            get { return "Ngay bat dau: " + _ngayBatDau + " -- Ngay ket thuc: " + _ngayKetThuc; }
        }

        public string NgayBatDau
        {
            get
            {
                return _ngayBatDau;
            }
        }

        public string NgayKetThuc
        {
            get { return _ngayKetThuc; }
        }
        #endregion

        #region ------ Compare ---------
        public void Sort_TenCoPhieu_ASC()
        {
            _danhSachCoPhieu.Sort(CoPhieu.Compare_TenCoPhieu_ASC);
        }

        public void Sort_ThayDoiGiaTheoNgay_DES()
        {
            _danhSachCoPhieu.Sort(CoPhieu.Compare_ThayDoiGiaTheoNgay_DES);
        }

        public void Sort_ThayDoiKhoiLuongTheoNgay_DES()
        {
            _danhSachCoPhieu.Sort(CoPhieu.Compare_ThayDoiKhoiLuongTheoNgay_DES);
        }
        #endregion
    }

}
